第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

JAVA使用Condition時(shí)中斷的一個(gè)疑問?

JAVA使用Condition時(shí)中斷的一個(gè)疑問?

冉冉說 2019-01-16 13:13:46
問題描述 在使用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ì)列。

查看完整回答
反對 回復(fù) 2019-02-12
  • 1 回答
  • 0 關(guān)注
  • 538 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)