java線程通信-生產者消費者

1 調用wait()方法可以讓線程等待,並釋放對象鎖,直到interrupt()方法中斷它或者另一個線程調用notify()或者notify()All喚醒

2.wait()方法可以帶個參數,此時不需要喚醒

3.調用notify()方法可以隨機選擇一個在該對象調用wait()方法的線程

4.notif和notifyAll()只能在同步方法或者同步塊中使用

5.wait()和sleep()的區別是:wait()方法調用時會釋放對象鎖,而sleep()不會

以下爲生產者消費者的例子:




public class ProRes {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Product product=new Product();
		Producer producer=new Producer(product);
		Consumer consumer=new Consumer(product);	}

}

class Product{
	int n;
	boolean valueset=false;//true表示有值可取,false便是需要放入新值
	//消費方法
	synchronized void get(){
		//如果沒有值,等待新值放入
		if(!valueset){
			try {
				wait();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		System.out.println(Thread.currentThread().getName()+"-Get:"+n);
		//將valuset設置爲false表示已取值
		valueset=false;
		//通知等待線程,放入新值
		notify();
	}
	//消費方法
	synchronized void put(int n){
		//如果沒有值,等待線程取值
		if (valueset) {
			try {
				wait();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		this.n=n;
		//將valueset設置爲true,表示值已放入
		valueset=true;
		System.out.println(Thread.currentThread().getName()+"-put:"+n);
		notify();
	}
}
class Producer implements Runnable{

	
		Product product;
		Producer(Product product){
			this.product=product;
			new Thread(this,"Producer").start();
		}
		public void run() {
			int k=0;
			for (int i = 0; i < 5; i++) {
				product.put(k++);
				
			}
	}
	
}
class Consumer implements Runnable{
	Product product;
	Consumer(Product product){
		this.product=product;
		new Thread(this,"Consumer").start();
	}

	public void run() {
		
		//消費五次
		for (int i = 0; i < 5; i++) {
			product.get();
			
		}
	}
	
}

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