Thread Communication

Thread 線程之間的通訊方式

1.共享對象

Thread之間經過對象的屬性來通訊。java

public class CallbackInstance {
	
	private boolean hasRunCompute;

	public synchronized  boolean hasRunCompute() {
		return hasRunCompute;
	}

	public synchronized  void setHasRunCompute(boolean hasRunCompute) {
		this.hasRunCompute = hasRunCompute;
	}
	
}

線程經過共享CallbackInstance對象,查詢CallbackInstance的flag狀態來做爲標識。ios

好比說執行一個大型運算操做,執行到某一步須要其餘線程分別開始運算,當通知時other threads running。ide

public class ProcessCompute implements Runnable {

	private CallbackInstance callbackInstance;
	
	@Override
	public void run() {
		while(!callbackInstance.hasRunCompute()) {
			//do something
		}
	}
}

經過將標識放在while循環中檢查,這種方式會消耗CPU資源,會頻繁的去獲取鎖而後檢查標識狀態,直到標識發生改變。this

注意:須要共享對象的實例,即同一對象。spa

2.wait()、notify()、notifyAll()

public final void wait() throws InterruptedException;
public final native void wait(long timeout) throws InterruptedException;
public final native void notify();
public final native void notifyAll();

執行這幾種方式都須要持有鎖。線程進入Synchronized代碼塊或者Synchronized method,若是遇到wait() method,會釋放持有的鎖,進入對象的等待池等待喚醒或者到指定timeout時間切換爲Runnalble(可運行)狀態。當有線程執行notify()時,會喚醒在等待池中第一個執行wait()的線程,FIFO(First In - First Out)先進先出的概念。執行notifyAll()喚醒等待池中的all threads.線程

喚醒的thread會從等待池移除,變爲可運行(Runnable)狀態。code

Application scenarios對象

現實中KFC的櫃檯人員和生產者,當櫃檯人員沒有可售賣的商品時則會處於等待狀態,此時至關於調用wait()方法,當廚房工做人員生產商品後則會通知櫃檯人員來取,根據售賣的前後順序進行獲取(notify)。資源

待續。it

相關文章
相關標籤/搜索