Java多線程 9 多個生產者和消費者

多個生產者和消費者的時候,需要考慮更多情況

package thread;

/*
對於多個生產者和消費者。

爲什麼要定義while判斷標記。
原因:讓被喚醒的線程再一次判斷標記。

爲什麼定義notifyAll,
因爲需要喚醒對方線程。因爲只用notify,容易出現只喚醒本方線程的情況。導致程序中的所有線程都等待。
*/

public class Thread_6_ProducerConsumerDemo2 {
	public static void main(String[] args) 
	{
		Resource r = new Resource();

		Producer pro = new Producer(r);
		Consumer con = new Consumer(r);

		Thread t1 = new Thread(pro);
		Thread t2 = new Thread(pro);
		Thread t3 = new Thread(con);
		Thread t4 = new Thread(con);

		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}

class Resource
{
	private String name;
	private int count = 1;
	private boolean flag = false;
	
	public synchronized void set(String name)
	{
		//這裏的while循環保證了某一方執行notify之後如果不小心被喚醒的是本方,則會被再次等待
		while(flag)
			try{this.wait();}catch(Exception e){}
		this.name = name+"--"+count++;

		System.out.println(Thread.currentThread().getName()+"...生產者.."+this.name);
		flag = true;
		//這裏的notifyAll()會喚醒所有生產者和消費者,避免了同一類的所有角色都進入wait狀態的風險
		this.notifyAll();
	}

	public synchronized void out()
	{
		while(!flag)
			try{wait();}catch(Exception e){}
		System.out.println(Thread.currentThread().getName()+"...消費者........."+this.name);
		flag = false;
		this.notifyAll();
	}
}

class Producer implements Runnable{
	private Resource res;

	Producer(Resource res){
		this.res = res;
	}
	
	public void run(){
		while(true)	{
			res.set("+商品+");
		}
	}
}

class Consumer implements Runnable{
	private Resource res;

	Consumer(Resource res){
		this.res = res;
	}
	
	public void run(){
		while(true){
			res.out();
		}
	}
}


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