標籤:

CyclicBarrier

CyclicBarrier譯為環形柵欄。參照JDK文檔:

A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.

A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue.

CyclicBarrier是多線程之間同步的工具,適用于于多個線程互相等待,如果有一個線程沒有達到barrier,其他線程會在barrier之前等待,然後一起越過barrier。

class Worker implements Runnable { CyclicBarrier cyclicBarrier; public Worker(CyclicBarrier cyclicBarrier) { this.cyclicBarrier = cyclicBarrier; } @Override public void run() { try { TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(10)); System.out.println(Thread.currentThread().getName() + "到達柵欄"); cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "越過柵欄"); }}class BarrierAction implements Runnable { @Override public void run() { try { System.out.println(Thread.currentThread().getName() +" start"); TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(10)); System.out.println(Thread.currentThread().getName() +" end"); } catch (InterruptedException e) { e.printStackTrace(); } }}public class Test { public static void main(String[] args) throws InterruptedException { int num = 10; CyclicBarrier cyclicBarrier = new CyclicBarrier(num, new BarrierAction()); for (int i = 0; i < num; i++) { Thread thread = new Thread(new Worker(cyclicBarrier)); thread.start(); } }}輸出結果Thread-1到達柵欄Thread-2到達柵欄Thread-3到達柵欄Thread-9到達柵欄Thread-4到達柵欄Thread-7到達柵欄Thread-5到達柵欄Thread-0到達柵欄Thread-6到達柵欄Thread-8到達柵欄Thread-8 startThread-8 endThread-8越過柵欄Thread-1越過柵欄Thread-3越過柵欄Thread-2越過柵欄Thread-9越過柵欄Thread-5越過柵欄Thread-6越過柵欄Thread-0越過柵欄Thread-7越過柵欄Thread-4越過柵欄

通過測試結果可知,cyclicBarrier由最後一個達到barrier的線程執行。

參考資料:CyclicBarrier (Java Platform SE 8 )

推薦閱讀:

Mutex and Spinlock

TAG:並發 |