Java 同步方式 (2) —— wait和notify/notifyall

來源:互聯網
上載者:User

Java 中除了關鍵字 synchronized 能夠實現線程同步外,還可以使用 wait 和 notify/notify 實現同步。

wait 方法是使擁有當前對象(object)的線程(thread)放棄鎖(release lock),進入睡眠狀態

notify 通知該對象(object)因上面調用wait而等待的某一進程重新喚醒啟動

notifyAll 通知在對象(object)上因調用wait而等待的所有進程啟動,這些進程根據優先順序順序執行


一個線程在其生命週期內總是處於某種狀態:

  1. 建立: 當一個線程對象被聲明並建立後,它處於“建立”狀態;
  2. 就緒:線程對象調用 start() 方法後,將進入“就緒”狀態,處於“就緒”狀態的線程不是立即執行,而是進入就緒隊列,等待CPU;
  3. 運行:當就緒隊列中具有最高優先順序的就緒線程被調度並獲得CPU時,便進入“運行”狀態,執行 run() 方法,run 方法中定義了線程的操作和功能;
  4. 非運行:處於“運行”狀態的線程可能因為某些原因 (例如人為掛起)進入“非運行”狀態,讓出CPU並臨時中止自己的執行;
  5. 停止:線程完成了它的全部工作或調用 stop() 方法強制中止線程,線程就進入“停止”狀態。


wait 與 sleep 區別

 

wait

sleep

歸屬類

屬於Object類(java.lang.Object)

屬於Thread類(java.lang.Thread),靜態方法

釋放鎖

釋放了鎖,其它線程同步塊或方法

沒有釋放鎖,不出讓系統資源(如cpu)

中斷喚醒

wait一般不會加時間限制,而是判斷是否滿足符合條件;

如果符合條件,則notify/notifyall喚醒

sleep(milliseconds)後自動喚醒,

如果時間不到可用interrupt()強制中斷

適用範圍

同步方法或同步塊使用(synchronized)

任何地方都可使用(main、thread線程)

捕獲異常

必須捕獲異常(try/catch)

不需要捕獲異常

wait - sleep 樣本(區別)

package com.homer.thread;public class waitsleep {public static void main(String[] args) {ThreadDemo th = new ThreadDemo();th.start();System.out.println("thread is starting...");synchronized (th) {try {System.out.println("Waiting for th to complete...");//th.wait(1000);// 等待1秒後,立刻執行th.wait();// 線程等待,notify喚醒後執行} catch (Exception e) {e.printStackTrace();}System.out.println("Total is : " + th.total);// 線程喚醒後,執行}}}class ThreadDemo extends Thread {int total;@Overridepublic void run(){try {Thread.sleep(2000);// 睡眠2秒synchronized(this){System.out.println("Thread is running...");for(int i=0; i<10; i++) {total += i;System.out.println("i = " + i + "; total = " + total);if(i==5) {System.out.println("i = 5 sleep(3000)");Thread.sleep(3000);// i = 5時,睡眠3秒}}this.notify();}} catch (Exception e) {e.printStackTrace();}}}

運行結果:

thread is starting...
Waiting for th to complete...
Thread is running...
i = 0; total = 0
i = 1; total = 1
i = 2; total = 3
i = 3; total = 6
i = 4; total = 10
i = 5; total = 15
i = 5 sleep(3000)
i = 6; total = 21
i = 7; total = 28
i = 8; total = 36
i = 9; total = 45
Total is : 45

================================

wait - notify 樣本(生產者 - 消費者)

package com.homer.thread;public class waitnotify {public static void main(String[] args) {Q q = new Q();new Producer(q);new Consumer(q);}}class Producer implements Runnable {Q q = null;public Producer(Q q) {this.q = q;(new Thread(this, "Producer")).start();}@Overridepublic void run() {int i = 0;while(i<5) {q.put(i++);}}}class Consumer implements Runnable {Q q = null;public Consumer(Q q) {this.q = q;(new Thread(this, "Consumer")).start();}@Overridepublic void run() {while(q.get()<5){}}}class Q {int n;boolean valueSet = false;public synchronized int get() {if(!valueSet) {// if valueSet == false,wait else try to got valuetry {wait();} catch (InterruptedException e) {e.printStackTrace();}} System.out.println("Get n : " + n);valueSet = false;notify();return n;}public synchronized void put(int n) {if(valueSet) {// if valueSet == true,already have value so wait fetch,else put try {wait();} catch (InterruptedException e) {e.printStackTrace();}}this.n = n;System.out.println("Put n : " + n);valueSet = true;notify();}}

運行結果:

Put n : 0
Get n : 0
Put n : 1
Get n : 1
Put n : 2
Get n : 2
Put n : 3
Get n : 3
Put n : 4
Get n : 4

首先兩個線程啟動,他們的執行佔用CPU多少隨機,但是這裡因為加了一個鎖的Boolean型變數,而控制了put與set. 

首先:建立了一個對象Q,建立了一個Producer,一個Consumer,這兩個對象在構造方法中啟動了線程. 
第一步:
    對於Producer來說,會首先去調用put方法,因為valueSet是預設值是false,所以在Q的put方法不執行wait 而是執行 this.n = n 賦值操作,執行完畢後設定為valueSet = true
    對於Consumer來說,會首先去調用get方法,因為valueSet是預設值是false,所以該線程會執行wait(等待valueSet 賦值狀態為true)
第二步:
   對於Producer來說,因為valueSet已經變成true,所以會wat. 
   對於Consumer來說,因為valueSet已經變成true,所以會執行下面的code(get value),然後設定valueSet為false.
第三步:
   Producer執行put方法,因為valueSet為false
   Consumer等待(重複第一步)
依次類推,方法執行... 

這裡關鍵是加了一個共用的變數 valueSet 來判是該取值get,還是put值。當然有了wait跟notify才使它成為了可以實現的。 
但是不管怎樣,wait是使目前控制該對象(Q的對象q)的線程wait(等待),notify是使前面在該對象上面wait的方法繼續執行. 


範例程式碼下載



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.