多線程之多消費者與生產者

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 才能保證程序正常運轉.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章