執行緒同步工具Condition詳解

2021-10-06 04:37:15 字數 3047 閱讀 8336

condition可以代替object監視器方法( wait , notify和notifyall ),必須和lock配合使用, lock替換synchronized方法和語句的使用, condition取代了物件監視器方法的使用。可以使某個執行緒掛起,直到其他執行緒喚醒,就像object.wait()方法,乙個condition例項本質上繫結到乙個鎖。 要獲得特定condition例項,請使用llock的newcondition()方法。

可以看出它是乙個介面,所以其邏輯必須由實現類代替

獲取condition

private reentrantlock lock =

newreentrantlock()

;private condition condition = lock.

newcondition()

;

關於reentrantlock請移步併發程式設計之reentrantlock解析

* @return the condition object

*/public condition newcondition()

//真正的實現類

final conditionobject newcondition()

重要方法

/**

* 阻塞該執行緒,直到其他執行緒signal()方法或者signalall()方法,亦或者被其他執行緒打斷,會清楚中斷狀態

***/

void

await()

throws interruptedexception;

/**

* 在await()方法上設定了超時時間而已

***/

boolean

await

(long time, timeunit unit)

throws interruptedexception;

/**

* 喚醒阻塞的執行緒如果有多個執行緒阻塞,隨機喚醒乙個

***/

void

signal()

;

/**

* 喚醒所有阻塞的執行緒

***/

void

signalall()

;

案例分析condition在阻塞佇列應用的比較多如arrayblockingqueue的put方法

/**

* 將指定的元素加入佇列,如果佇列滿了發生阻塞

** @throws interruptedexception

* @throws nullpointerexception

*/public

void

put(e e)

throws interruptedexception

finally

}

關於arrayblockingqueue請移步arrayblockingqueue詳解

/**

* 描述: 演示condition的基本用法

*/public

class

conditiondemo1

finally

}void

method2()

finally

}public

static

void

main

(string[

] args)

throws interruptedexception

catch

(interruptedexception e)}}

).start()

; conditiondemo1.

method1();}}

/**

* 描述: 演示用condition實現生產者消費者模式

*/public

class

conditiondemo2

class

consumer

extends

thread

private

void

consume()

catch

(interruptedexception e)

} queue.

poll()

; notfull.

signalall()

; system.out.

println

("從佇列裡取走了乙個資料,佇列剩餘"

+ queue.

size()

+"個元素");

}finally}}

}class

producer

extends

thread

private

void

produce()

catch

(interruptedexception e)

} queue.

offer(1

);notempty.

signalall()

; system.out.

println

("向佇列插入了乙個元素,佇列剩餘空間"

+(queuesize - queue.

size()

));}

finally}}

}}

併發程式設計四(4) 執行緒同步 Condition

import threading import time def consumer cond with cond print consumer before wait cond.wait 等待消費 相當於程序就緒狀態 print consumer after wait def producer co...

工具類之Condition

再次看到 condition,第一感覺還是覺得它和 mutex的功能是一樣的,沒必要存在。心裡這麼想,其實自己也知道怎麼可能多餘呢?老老實實的再分析一下 這次一定要把理解出來的內容記下來!都怪平時寫 太少,用到 condition的情況更少,偶爾想用的時候又忘記怎麼用,於是就算了。拿一段condit...

JUC同步條件變數Condition

condition 是乙個多執行緒協調通訊的工具類,可以讓某些執行緒一起等待某個條件 condition 只有滿足條件時,執行緒才會被喚醒,參考synchronized wait notify notifyall condition 的基本使用 1.構造帶有lock和condition的執行緒 2....