標籤:鎖 並發 java並發編程
柵欄類似閉鎖,但是它們是有區別的.
閉鎖用來等待事件,而柵欄用於等待其他線程.什麼意思呢?就是說閉鎖用來等待的事件就是countDown事件,只有該countDown事件執行後所有之前在等待的線程才有可能繼續執行;而柵欄沒有類似countDown事件控制線程的執行,只有線程的await方法能控制等待的線程執行.
CyclicBarrier強調的是n個線程,大家相互等待,只要有一個沒完成,所有人都得等著。
情境分析:10個人去春遊,規定達到一個地點後才能繼續前行.代碼如下
import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;class CyclicBarrierWorker implements Runnable { private int id; private CyclicBarrier barrier; public CyclicBarrierWorker(int id, final CyclicBarrier barrier) { this.id = id; this.barrier = barrier; } @Override public void run() { // TODO Auto-generated method stub try { System.out.println(id + " th people wait"); barrier.await(); // 大家等待最後一個線程到達 } catch (InterruptedException | BrokenBarrierException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}public class TestCyclicBarrier { public static void main(String[] args) { int num = 10; CyclicBarrier barrier = new CyclicBarrier(num, new Runnable() { @Override public void run() { // TODO Auto-generated method stub System.out.println("go on together!"); } }); for (int i = 1; i <= num; i++) { new Thread(new CyclicBarrierWorker(i, barrier)).start(); } }}
輸出
1 th people wait2 th people wait3 th people wait4 th people wait5 th people wait7 th people wait8 th people wait6 th people wait9 th people wait10 th people waitgo on together!
Java並發編程之柵欄(CyclicBarrier)詳解