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();
}
}
生产者消费者问题
最新推荐文章于 2023-04-26 09:27:27 发布
本文探讨了并发环境中资源管理的关键技术,通过使用生产者和消费者线程模型,实现资源的高效分配与利用。详细介绍了如何通过同步机制确保线程间的正确交互,以及资源的合理获取与释放。

3458

被折叠的 条评论
为什么被折叠?



