生产者消费者示例二

/*
需求:
	多生产,多消费
思路:
步骤:
*/

class Resource
{
	private String name;
	private int num = 1;
	private boolean flag;

	public synchronized void set(String name)
	{
		//对于多生产者,此处需要用while来判断,如果不用while的话,当线程被唤醒后
		//不去判断标记,直接生产可能会存在问题,导致之前生产的不会被消费
		while(flag)
		{
			try
			{
				wait();
			}
			catch (InterruptedException e)
			{

			}
		}
		this.name = name + num;
		System.out.println(Thread.currentThread().getName() + "...生产者..." + this.name);
		num++;
		flag = true;
		//另外这里需要改为notifyAll();因为notify是任意唤醒一个线程,假设唤醒的依然是生产者
		//会导致所有线程处于等待状态
		//notify();
		notifyAll();
	}

	public synchronized void out()
	{
		//对于多生产者,此处需要用while来判断,如果不用while的话,当线程被唤醒后
		//不去判断标记,直接消费可能会存在问题,导致之前生产的会被消费多次
		while(!flag) 
		{
			try
			{
				wait();
			}
			catch (InterruptedException e)
			{
			}
		}
		System.out.println("-------"+ Thread.currentThread().getName() + "... 消费者..." +name);
		//num--;
		flag = false;
		//另外这里需要改为notifyAll();因为notify是任意唤醒一个线程,假设唤醒的依然是消费者
		//会导致所有线程处于等待状态
		//notify();
		notifyAll();
	}
}

class Producer implements Runnable
{
	private Resource r;

	public Producer(Resource r)
	{
		this.r = r;
	}

	public void run()
	{
		while(true)
		{
			r.set("烤鸭");
		}
	}
}

class Consumer implements Runnable
{
	private Resource r;

	public Consumer(Resource r)
	{
		this.r = r;
	}

	public void run()
	{
		while(true)
		{
			r.out();
		}
	}
}


class  MultiProducerConsumer
{
	public static void main(String[] args) 
	{
		Resource r = new Resource();
		Producer pro1_runnable = new Producer(r);
		Producer pro2_runnable = new Producer(r);
		Consumer con1_runnable = new Consumer(r);
		Consumer con2_runnable = new Consumer(r);

		Thread pro1_thread = new Thread(pro1_runnable);
		Thread pro2_thread = new Thread(pro2_runnable);
		Thread con1_thread = new Thread(con1_runnable);
		Thread con2_thread = new Thread(con2_runnable);

		pro1_thread.start();
		pro2_thread.start();
		con1_thread.start();
		con2_thread.start();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值