天天看點

Groovy裡使用CountDownLatch

Latch的字面意思:彈簧鎖

Groovy裡使用CountDownLatch

CountDownLatch是java.util.concurrent包裡的一個同步工具類。

CountDownLatch的構造函數,接收一個類型為整型的參數,代表CountDownLatch所在的線程,在執行await方法後能夠傳回,所需要在其他線程内調用其countDown方法的次數。

Groovy裡使用CountDownLatch
Groovy裡使用CountDownLatch
timer.schedule新啟動了一個線程,在新線程裡調用countDown,而主線程執行await進入阻塞狀态,待新線程調用一次countDown之後,主線程立即從await方法的阻塞狀态中傳回。

package jerry;

import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit

CountDownLatch called = new CountDownLatch(1)
println "main thread id: " + Thread.currentThread().getId();

Timer timer = new Timer()
timer.schedule(new TimerTask() {
    void run() {
        println "call countDown in another thread: " + Thread.currentThread().getId();
        called.countDown()
    }
}, 220)

println "before calling called.await in main thread: " + Thread.currentThread().getId();
called.await(10, TimeUnit.SECONDS)
println "after calling called.await in main thread: " + Thread.currentThread().getId();      

繼續閱讀