多线程之多消费者与生产者

package PAndCList;

public class C {
	private Service service;
	public void eat(Service service) throws InterruptedException{
		
		synchronized (service) {
			while(Service.list.size()==0){
				System.out.println(Thread.currentThread().getName());
				System.out.println("等待...");
				service.wait();
			}
			System.out.println(Thread.currentThread().getName() + " 消费了" + Service.list.get(0));
			Service.list.remove(0);
			System.out.println("我想唤醒 生产者");
			service.notify();
		}
		
	}
}





package PAndCList;

public class P {
	
	private Service service;
	public void create(Service service) throws InterruptedException{
		
		synchronized (service) {
			if(Service.list.size()!=0){
				service.wait();
			}
			System.out.println(Thread.currentThread().getName() + " 生产了一个");
			service.list.add("Aug");
			System.out.println("生产 " + Service.list.get(0));
			System.out.println("我想唤醒了 所有的消费者");
			service.notifyAll();
		}
	}
}




package PAndCList;

public class TestMain {

	public static void main(String[] args) throws InterruptedException {
		Service service = new Service();
		P p = new P();
		C c = new C();
		C c1 = new C();
		C c2 = new C();
		C c3 = new C();
		C c4 = new C();
		C c5 = new C();
		
		
		ThreadC threadC = new ThreadC(service, c);
		threadC.start();
		
		ThreadC threadC1 = new ThreadC(service, c1);
		threadC1.start();
		
		ThreadC threadC2 = new ThreadC(service, c2);
		threadC2.start();

		ThreadC threadC3 = new ThreadC(service, c3);
		threadC3.start();
		
		ThreadC threadC4 = new ThreadC(service, c4);
		threadC4.start();
		
		ThreadC threadC5 = new ThreadC(service, c5);
		threadC5.start();
		
		Thread.sleep(1000);
		
		ThreadP threadP = new ThreadP(service, p);
		threadP.start();
	}
}

为什么C中使用while? P中使用 NotifyAll? 

1. 如果P使用Notify() C 使用 if  那么 C 中唤醒的则是C 程序会报错。

2. 如果P使用Notify() C 使用 while 那么 C中是处于死锁状态.

3. 只有P使用 NotifyAll C 使用 while 才能保证程序正常运转.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值