問題描述
在使用Condition進(jìn)行線程的掛起和喚醒的時(shí)候,我經(jīng)常見到以下的使用方法 Thread1調(diào)用Await()方法等待Thread2的Signal喚醒,為了避免長時(shí)間的等待,又加了超時(shí)的限制,所以Thread1通常寫成Condition.await(long,TimeUnit)。但是事實(shí)真的是在超時(shí)之后,Condition就會(huì)返回嗎?
問題出現(xiàn)的環(huán)境背景及自己嘗試過哪些方法
我翻看了一下相關(guān)的源碼,發(fā)現(xiàn)并不是這個(gè)樣子的??梢酝ㄟ^以下的代碼來檢測
相關(guān)代碼
// 請把代碼文本粘貼到下方(請勿用圖片代替代碼)
public class TestConditionAwait {
private static ReentrantLock lock = new ReentrantLock();
private static Logger Log = LoggerFactory.getLogger(TestConditionAwait.class);
public static void main(String[] args) throws InterruptedException {
final Condition condition = lock.newCondition();
final Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
try {
Thread.currentThread().setName("ConditionAwait-Thread-");
Log.error(Thread.currentThread().getName() + " beforeAwaitTime:" + System.currentTimeMillis());
condition.await(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Log.error(Thread.currentThread().getName() + " finishAwaitTime:" + System.currentTimeMillis());
}finally {
lock.unlock();
Log.error(Thread.currentThread().getName() + " unlockTime:" + System.currentTimeMillis());
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("ConditionSignal-Thread-");
try{
Log.error(Thread.currentThread().getName() + " getLockTime:" + System.currentTimeMillis());
thread1.interrupt();
lock.lock();
long currentTime = System.currentTimeMillis();
while (System.currentTimeMillis() - currentTime < 8000){
}
condition.signal();
Log.error(Thread.currentThread().getName() + " signalTime:" + System.currentTimeMillis());
}catch (Exception e){
}finally {
lock.unlock();
Log.error(Thread.currentThread().getName() + " unlockTime:" + System.currentTimeMillis());
}
}
});
thread1.start();
Thread.sleep(50);
thread2.start();
}
}
你期待的結(jié)果是什么?實(shí)際看到的錯(cuò)誤信息又是什么?
1 回答

慕哥9229398
TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超6個(gè)贊
你代碼的結(jié)果是這樣來的,thread1在await后放棄了鎖,thread2獲得鎖并開始循環(huán),5000ms后,thread1從條件變量等待隊(duì)列里面被喚醒,此時(shí)thread1要重新獲得鎖才能繼續(xù)執(zhí)行下去,但是鎖被thread2占用,所以不得不等到thread2釋放鎖之后,也就是8000ms之后才能繼續(xù)執(zhí)行。
thread1從條件變量等待隊(duì)列中被超時(shí)喚醒后又進(jìn)入了鎖等待隊(duì)列。
添加回答
舉報(bào)
0/150
提交
取消