JAVA中的wait和notify
阿新 • • 發佈:2017-07-20
try object ted 並不是 阻塞 main nbsp star oid
1 package com.runnabledemo; 2 3 public class waitnotifydemo01 { 4 public static void main(String[]args)throws Exception { 5 final Object obj = new Object(); 6 Thread t1 = new Thread() { 7 public void run() { 8 synchronized (obj) { 9 try{ 10 obj.wait(); 11 System.out.println("Thread 1 wake up."); 12 } catch (InterruptedException e) { 13 } 14 } 15 } 16 }; 17 t1.start(); 18 Thread.sleep(1000);//We assume thread 1 must start up within 1 sec.19 Thread t2 = new Thread() { 20 public void run() { 21 synchronized (obj) { 22 obj.notifyAll(); 23 System.out.println("Thread 2 sent notify."); 24 } 25 } 26 }; 27 t2.start(); 28 }29 }
輸出結果為:
Thread 2 sent notify.
Thread 1 wake up.
分析:t1 啟動後執行 obj.wait() 時,進入阻塞狀態,讓出時間片並釋放鎖,等待其他線程的喚醒。然後 t2 獲取到 obj,並喚醒 t1,待 t2 執行完畢,釋放鎖後,t1 再繼續執行。
notify()就是對對象鎖的喚醒操作。但有一點需要註意的是notify()調用後,並不是馬上就釋放對象鎖的,而是在相應的synchronized(){}語句塊執行結束,自動釋放鎖後,JVM會在wait()對象鎖的線程中隨機選取一線程,賦予其對象鎖,喚醒線程,繼續執行。這樣就提供了在線程間同步、喚醒的操作。
JAVA中的wait和notify