天天看點

多線程程式設計--異步轉同步之CountDownLatch

在日常開發中,我們經常會碰到這樣的情況:一些異步請求我們需要等到接收到請求後再執行下一步動作,這時我們就需要把異步動作轉為同步動作。

java中給我們提供了一個countdownlatch類來實作這個功能。

先看下countdownlatch的官方定義:

a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

意思是:countdownlatch是一個同步助手,它可以使一個或多個線程等待,直到一系列在其他線程中執行的動作完成(這些線程才被喚醒)

具體如何使用呢?

看下這段文檔:

a <code>countdownlatch</code> is initialized with a givencount. the<code>await()</code> methods block until the current count reaches zero due to invocations of the countdown() method,

after which all waiting threads are released and any subsequent invocations of<code>await()</code> return immediately. 

a useful property of a<code>countdownlatch</code> is that it doesn‘t require that threads calling<code>countdown</code> wait for the count to reach zero before proceeding, it simply prevents

any thread from proceeding past an<code>await()</code> until all threads could pass. 

這句翻譯出來會有偏差,大家自己體會吧

詳細用例:

繼續閱讀