wait和notify的理解與使用


1.對於wait()和notify()的理解

對於wait()和notify()的理解,還是要從jdk官方文檔中開始,在Object類方法中有:

void notify() 
Wakes up a single thread that is waiting on this object’s monitor. 
譯:喚醒在此對象監視器上等待的單個線程

void notifyAll() 
Wakes up all threads that are waiting on this object’s monitor. 
譯:喚醒在此對象監視器上等待的所有線程

void wait( ) 
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll( ) method for this object. 
譯:導致當前的線程等待,直到其他線程調用此對象的notify( ) 方法或 notifyAll( ) 方法

void wait(long timeout) 
Causes the current thread to wait until either another thread invokes the notify( ) method or the notifyAll( ) method for this object, or a specified amount of time has elapsed. 
譯:導致當前的線程等待,直到其他線程調用此對象的notify() 方法或 notifyAll() 方法,或者指定的時間過完。

void wait(long timeout, int nanos) 
Causes the current thread to wait until another thread invokes the notify( ) method or the notifyAll( ) method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed. 
譯:導致當前的線程等待,直到其他線程調用此對象的notify( ) 方法或 notifyAll( ) 方法,或者其他線程打斷了當前線程,或者指定的時間過完。

上面是官方文檔的簡介,下面我們根據官方文檔總結一下:

  • wait( ),notify( ),notifyAll( )都不屬於Thread類,而是屬於Object基礎類,也就是每個對象都有wait( ),notify( ),notifyAll( ) 的功能,因為每個對象都有鎖,鎖是每個對象的基礎,當然操作鎖的方法也是最基礎了。

  • 當需要調用以上的方法的時候,一定要對競爭資源進行加鎖,如果不加鎖的話,則會報 IllegalMonitorStateException 異常

  • 當想要調用wait( )進行線程等待時,必須要取得這個鎖對象的控制權(對象監視器),一般是放到synchronized(obj)代碼中。

  • 在while循環里而不是if語句下使用wait,這樣,會在線程暫停恢復后都檢查wait的條件,並在條件實際上並未改變的情況下處理喚醒通知

  • 調用obj.wait( )釋放了obj的鎖,否則其他線程也無法獲得obj的鎖,也就無法在synchronized(obj){ obj.notify() } 代碼段內喚醒A。

  • notify( )方法只會通知等待隊列中的第一個相關線程(不會通知優先級比較高的線程)

  • notifyAll( )通知所有等待該競爭資源的線程(也不會按照線程的優先級來執行)

  • 假設有三個線程執行了obj.wait( ),那么obj.notifyAll( )則能全部喚醒tread1,thread2,thread3,但是要繼續執行obj.wait()的下一條語句,必須獲得obj鎖,因此,tread1,thread2,thread3只有一個有機會獲得鎖繼續執行,例如tread1,其余的需要等待thread1釋放obj鎖之后才能繼續執行。

  • 當調用obj.notify/notifyAll后,調用線程依舊持有obj鎖,因此,thread1,thread2,thread3雖被喚醒,但是仍無法獲得obj鎖。直到調用線程退出synchronized塊,釋放obj鎖后,thread1,thread2,thread3中的一個才有機會獲得鎖繼續執行。

2.wait和notify簡單使用示例

 1 public class WaitNotifyTest {
 2  
 3     // 在多線程間共享的對象上使用wait
 4     private String[] shareObj = { "true" };
 5  
 6     public static void main(String[] args) {
 7         WaitNotifyTest test = new WaitNotifyTest();
 8         ThreadWait threadWait1 = test.new ThreadWait("wait thread1");
 9         threadWait1.setPriority(2);
10         ThreadWait threadWait2 = test.new ThreadWait("wait thread2");
11         threadWait2.setPriority(3);
12         ThreadWait threadWait3 = test.new ThreadWait("wait thread3");
13         threadWait3.setPriority(4);
14  
15         ThreadNotify threadNotify = test.new ThreadNotify("notify thread");
16  
17         threadNotify.start();
18         threadWait1.start();
19         threadWait2.start();
20         threadWait3.start();
21     }
22  
23     class ThreadWait extends Thread {
24  
25         public ThreadWait(String name){
26             super(name);
27         }
28  
29         public void run() {
30             synchronized (shareObj) {
31                 while ("true".equals(shareObj[0])) {
32                     System.out.println("線程"+ this.getName() + "開始等待");
33                     long startTime = System.currentTimeMillis();
34                     try {
35                         shareObj.wait();
36                     } catch (InterruptedException e) {
37                         e.printStackTrace();
38                     }
39                     long endTime = System.currentTimeMillis();
40                     System.out.println("線程" + this.getName() 
41                             + "等待時間為:" + (endTime - startTime));
42                 }
43             }
44             System.out.println("線程" + getName() + "等待結束");
45         }
46     }
47  
48     class ThreadNotify extends Thread {
49  
50         public ThreadNotify(String name){
51             super(name);
52         }
53  
54  
55         public void run() {
56             try {
57                 // 給等待線程等待時間
58                 sleep(3000);
59             } catch (InterruptedException e) {
60                 e.printStackTrace();
61             }
62             synchronized (shareObj) {
63                 System.out.println("線程" + this.getName() + "開始准備通知");
64                 shareObj[0] = "false";
65                 shareObj.notifyAll();
66                 System.out.println("線程" + this.getName() + "通知結束");
67             }
68             System.out.println("線程" + this.getName() + "運行結束");
69         }
70     }
71 }

運行結果:

線程wait thread1開始等待
線程wait thread3開始等待
線程wait thread2開始等待
線程notify thread開始准備通知
線程notify thread通知結束
線程notify thread運行結束
線程wait thread2等待時間為:2998
線程wait thread2等待結束
線程wait thread3等待時間為:2998
線程wait thread3等待結束
線程wait thread1等待時間為:3000
線程wait thread1等待結束

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM