class Demo4
{
public static void main(String[] args)
{
Resourse r = new Resourse();
new Thread(new Producer(r)).start();
new Thread(new Producer(r)).start();
new Thread(new Customer(r)).start();
new Thread(new Customer(r)).start();
}
}
class Resourse
{
private String name;
private int num=1;
private boolean flag=false;
public synchronized void put(String name)
{
while(flag)try{this.wait();}catch(Exception e){}
this.name=name+"--"+num++;
System.out.println(Thread.currentThread().getName()+"--生产者--"+this.name);
flag=true;
this.notifyAll();
}
public synchronized void get()
{
while(!flag)try{this.wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"----消费者----"+this.name);
flag=false;
this.notifyAll();
}
}
class Producer implements Runnable
{
private Resourse r;
Producer(Resourse r)
{
this.r=r;
}
public void run()
{
int i=0;
while(true)
{
if(i==0)
r.put("商品1");
else
r.put("商品2");
i=(i+1)%2;
}
}
}
class Customer implements Runnable
{
private Resourse r;
Customer(Resourse r)
{
this.r=r;
}
public void run()
{
while(true)
r.get();
}
}
生产者消费者问题
最新推荐文章于 2024-07-18 14:16:46 发布