Lock和Condition物件的使用

2021-08-01 18:17:24 字數 1346 閱讀 9405

condition的await()方法

void await()

throws interruptedexception

導致當前執行緒等到發訊號或interrupted 。

在所有情況下,在此方法返回之前,當前執行緒必須重新獲取與此條件相關的鎖。 當執行緒返回時,它保證保持此鎖。

實現兩個執行緒交替執行的案例:

class car finally 

}public void

buffed() finally

}public void

waitforwaxing() throws interruptedexception finally

}public void

waitforbuffing() throws interruptedexception finally

}}class waxon implements runnable

@override

public void

run()

} catch (interruptedexception e)

system.out.println("ending wax on task");}}

class waxoff implements runnable

@override

public void

run()

} catch (interruptedexception e)

system.out.println("ending wax off task");}}

public class waxomatic2

}

wax on!

wax off!

wax on!

wax off!

wax on!

wax off!

wax on!

wax off!

wax on!

wax off!

wax on!

wax off!

wax on!

wax off!

wax on!

wax off!

wax on!

wax off!

wax on!

wax off!

wax on!

wax off!

wax on!

wax off!

wax on!

exiting via interrupt

ending wax on task

exiting via interrupt

ending wax off task

Lock和Condition實現多執行緒迴圈執行

我們可能有如下使用場景 a b c三個執行緒,業務需要a執行5遍,然後b執行10遍,然後c執行15遍,如此迴圈 這時候我們可以考慮用到lock的condition機制 public class locktest for int i 0 i 5 i number 2 c2.signal lock.un...

mutex和condition的用法

分享一下用到的mutex和condition用法。mutex一般有兩種使用情況,一種是單獨使用,保護臨界區。一種是和condition配合使用,可以等待某condition拿到之後再向下走。condition 有兩種signal形式,single和 broadcast,下面例子是signal的,做個...

redis中condition和unless的區別

1.註解的condition和unless的區別,condition對傳入值生效,unless對結果result生效,使用了錯誤的result導致報空錯誤 2.key鍵生成策略,不能再key中直接呼叫工具類的方法,將方法寫在同乙個類下,使用 root.target.methodname p0.att...