这是我根据“生产者和消费者”例子编写的,这个例子课件里有,你可以看看完之后自己写,我写这个只是交流交流,这个程序还有很多不合理的地方,需要改进,但由于本人技术有限只能写成这样了,没有写注释,你看了那个例子之后就很轻松的看懂了。
class Res
{
private int j;
private boolean flag=false;
public synchronized void add()
{
while(flag)
try
{
wait();
}
catch(Exception e)
{ }
System.out.println("j++:"+j++);
flag=true;
this.notifyAll();
}
public synchronized void sub()
{
while(!flag)
try
{
wait();
}
catch(Exception e)
{ }
System.out.println("j--:"+j--);
flag=false;
this.notifyAll();
}
}
class Zz implements Runnable
{
private Res z;
Zz(Res z)
{
this.z=z;
}
public void run()
{
while(true)
{
z.add();
}
}
}
class Zj implements Runnable
{
private Res j;
Zj(Res j)
{
this.j=j;
}
public void run()
{
while(true)
{
j.sub();
}
}
}
class Demotest
{
public static void main(String[] args)
{
Res r=new Res();
Zz sum= new Zz(r);
Thread t1=new Thread(sum);
Thread t2=new Thread(sum);
t1.start();
t2.start();
Zj sub1= new Zj(r);
Thread t3=new Thread(sub1);
Thread t4=new Thread(sub1);
t3.start();
t4.start();
}
} |