wait(),notify(),notifyAll()进行了详细的分析介绍
wait(): Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
notify(): Wakes up a single thread that is waiting on this object's monitor.
notifyAll(): Wakes up all threads that are waiting on this object's monitor.
這三個方法,都是Java語言提供的實現(xiàn)線程間阻塞(Blocking)和控制進(jìn)程內(nèi)調(diào)度(inter-process communication)的底層機(jī)制。在解釋如何使用前,先說明一下兩點(diǎn):
1. 正如Java內(nèi)任何對象都能成為鎖(Lock)一樣,任何對象也都能成為條件隊列(Condition queue)。而這個對象里的wait(), notify()和notifyAll()則是這個條件隊列的固有(intrinsic)的方法。
2. 一個對象的固有鎖和它的固有條件隊列是相關(guān)的,為了調(diào)用對象X內(nèi)條件隊列的方法,你必須獲得對象X的鎖。這是因為等待狀態(tài)條件的機(jī)制和保證狀態(tài)連續(xù)性的機(jī)制是緊密的結(jié)合在一起的。
(An object's intrinsic lock and its intrinsic condition queue are related: in order to call any of the condition queue methods on object X, you must hold the lock on X. This is because the mechanism for waiting for state-based conditions is necessarily tightly bound to the mechanism fo preserving state consistency)
根據(jù)上述兩點(diǎn),在調(diào)用wait(), notify()或notifyAll()的時候,必須先獲得鎖,且狀態(tài)變量須由該鎖保護(hù),而固有鎖對象與固有條件隊列對象又是同一個對象。也就是說,要在某個對象上執(zhí)行wait,notify,先必須鎖定該對象,而對應(yīng)的狀態(tài)變量也是由該對象鎖保護(hù)的。
為什么在執(zhí)行wait, notify時,必須獲得該對象的鎖?
這是因為,如果沒有鎖,wait和notify有可能會產(chǎn)生競態(tài)條件(Race Condition)。
編程:兩個線程交替打印26個英文字母(線程間的通信)
package com.hbut.test;
/**
?* 編程:兩個線程交替打印26個英文字母
?*
?*/
public class TestWaitAndNotify implements Runnable {
char start='a';
public synchronized void print() throws InterruptedException{ ?//注意:wait以及notify一定要在線程安全的環(huán)境下執(zhí)行,不然會發(fā)生競爭資源的。
notify(); ? ?//喚醒一個等待的線程
if(start<='z'){
System.out.println(Thread.currentThread().getName()+":"+start);
start++;
}
wait(); ? ? ?//該線程釋放鎖,進(jìn)入等待狀態(tài);需要被喚醒
}
@Override
public void run() {
while(start<='z'){
try {
print();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
總結(jié)
以上是生活随笔為你收集整理的wait(),notify(),notifyAll()进行了详细的分析介绍的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 把字符串中的数字找出来并按照升序排序
- 下一篇: Quartz以及代码实现--可以实现定时