面試題 3種執行緒阻塞喚醒的對比

2022-04-02 00:23:59 字數 2802 閱讀 7773

wait/notify

/**

* @author wgr

* @create 2020/12/29 -- 0:28

*/public class test6 catch (interruptedexception e)

system.out.println(thread.currentthread().getname()+"----被喚醒");

當a先睡眠的時候,b先去喚醒

當去掉鎖的**塊的時候

它的演示結果和上面一樣就不貼出來了

public class test6  catch (interruptedexception e) 

system.out.println(thread.currentthread().getname()+"----被喚醒");

}finally

},"a").start();

new thread(() ->finally

},"b").start();}}

await 流程每個條件變數其實就對應著乙個等待佇列,其實現類是 conditionobject,開始 thread-0 持有鎖,呼叫 await,進入 conditionobject 的 addconditionwaiter 流程,建立新的 node 狀態為 -2(node.condition),關聯 thread-0,加入等待佇列尾部

接下來進入 aqs 的 fullyrelease 流程,釋放同步器上的鎖

unpark aqs 佇列中的下乙個節點,競爭鎖,假設沒有其他競爭執行緒,那麼 thread-1 競爭成功

park 阻塞 thread-0

signal 流程

假設 thread-1 要來喚醒 thread-0

進入 conditionobject 的 dosignal 流程,取得等待佇列中第乙個 node,即 thread-0 所在 node

執行 transferforsignal 流程,將該 node 加入 aqs 佇列尾部,將 thread-0 的 waitstatus 改為 0,thread-3 的waitstatus 改為 -1

特點

當前執行緒呼叫 unsafe.park() 方法

檢查 _counter ,本情況為 0,這時,獲得 _mutex 互斥鎖

執行緒進入 _cond 條件變數阻塞

設定 _counter = 0

呼叫 unsafe.unpark(thread_0) 方法,設定 _counter 為 1

喚醒 _cond 條件變數中的 thread_0

thread_0 恢復執行

設定 _counter 為 0

呼叫 unsafe.unpark(thread_0) 方法,設定 _counter 為 1

當前執行緒呼叫 unsafe.park() 方法

檢查 _counter ,本情況為 1,這時執行緒無需阻塞,繼續執行

設定 _counter 為 0

常見面試題

面試題 3種執行緒阻塞喚醒的對比

wait notify author wgr create 2020 12 29 0 28 public class test6 catch interruptedexception e system.out.println thread.currentthread getname 被喚醒 當a先睡...

語言面試題 值的對比

許多人看到這道題目的時候都會嗤之以鼻,覺得非常簡單,於是就寫下下面的 偶爾可能還有個別人,會因為自己注意 寫的是0.0,而 是0而沾沾自喜,不過這樣的寫法均為錯誤的寫法,為什麼呢?因為float的表示方法的問題,float本身就是 精確的,精確度在小數點後6 7位,再往後的就不能保證資料的精確度 大...

執行緒的面試題目

1.子執行緒迴圈 10 次,接著主線程迴圈 100 次,接著又回到子執行緒迴圈 10 次,接著再回到主線程又迴圈 100 次,如此迴圈50次,試寫出 2.編寫乙個程式,開啟3個執行緒,這3個執行緒的id分別為a b c,每個執行緒將自己的id在螢幕上列印10遍,要求輸出結果必須按abc的順序顯示 如...