JAVA學習:線程通信

1.使用synchronized關鍵字時,可使用wait() , notify() , notifyAll()進行線程通信控制


**可以自定義一個變量作爲標誌位結合使用。

**調用wait()導致的程序阻塞並不是死鎖。


2.使用LOCK對象時,可使用Condition進行線程通信控制


import java.util.concurrent.locks.*;
class x{
	private ReentrantLock lock=new ReentrantLock();
	private Condition con=lock.newCondition();
	boolean flag=true;
	private void needLock(){
		lock.lock();
		try{
			//code
			if(!flag)
			con.await();
		    else
			con.signalAll();
		}
		catch(Exception e){//使用Condition方法時需要捕獲異常或聲明拋出
			System.out.println(e);
		}
		finally{
		lock.unlock();
		}
	}
	public static void main(String args[]){
	}
}
			


3.使用阻塞隊列BlockingQueue控制線程通信

作爲線程同步的工具 ,且有特徵:

當生產者線程試圖從BlockingQueue中放入元素,如果隊列已滿,則該線程被阻塞;

當消費者線程試圖從BlockingQueue中取出元素,如果隊列已空,則該線程被阻塞。

         


BlockingQueue包含以下實現類:


import java.util.concurrent.*;
class x extends Thread{
	private int i=1;
	private BlockingQueue<String> bq=null;
	x(BlockingQueue<String> bq){
		this.bq=bq;
	}
	public void run(){
		try{
			bq.put("Put "+i);//放入元素
			System.out.println(getName()+"	"+bq);
			i++;
		}
		catch(Exception e){
			System.out.println(e);
			System.out.println(getName()+" - FULLED");
		}
	}
	
	public static void main(String args[]){
		BlockingQueue<String> bq=new ArrayBlockingQueue<String>(1);
		new x(bq).start();
		new x(bq).start();
		new y(bq).start();
	}
}

class y extends Thread{
	private BlockingQueue<String> bq=null;
	y(BlockingQueue<String> bq){
		this.bq=bq;
	}
	public void run(){
		try{
			bq.take();
			System.out.println(getName()+"	"+bq);
			}
		catch(Exception e){
			System.out.println(e);
			System.out.println(getName()+" - EMPTY");
		}
	}
}
			

輸出結果:




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