class Res
{
privateString name;
privateint count=1;
privateboolean flag=false;
publicsynchronized void set(String name)
{
while(true)
{
while(flag)
{
try
{
this.wait();
}
catch(Exceptione)
{
}
}
this.name=name+"---"+count++;
System.out.println(Thread.currentThread().getName()+"生产者..."+this.name);
flag=true;
this.notifyAll();
}
}
publicsynchronized void get()
{
while(true)
{
while(!flag)
{
try
{
this.wait();
}
catch(Exceptione)
{
}
}
System.out.println(Thread.currentThread().getName()+"消费者.........."+this.name);
flag=false;
this.notifyAll();
}
}
}
class Pro implements Runnable
{
Resr;
Pro(Resr)
{
this.r=r;
}
publicvoid run()
{
r.set("商品");
}
}
class Cos implements Runnable
{
Resr;
Cos(Resr)
{
this.r=r;
}
publicvoid run()
{
r.get();
}
}
public class Demo
{
publicstatic void main(String args[])
{
Resr=new Res();
Prop=new Pro(r);
Cosc=new Cos(r);
Threadt1=new Thread(p);
Threadt2=new Thread(p);
Threadt3=new Thread(c);
Threadt4=new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();
}
}