多執行緒學習---CyclicBarrier
阿新 • • 發佈:2018-11-17
1.概述:
表示大家彼此等待,大家集合好後才出發,分散活動後又在指定地點碰面,這就好比整個公司的人員利用週末集體出去郊遊一樣,先各自從家出發到公司集合後,再同時出發到公園遊玩,在指定地點集合後再同時開始就餐,。。。
2.程式碼例項(跑步比賽)
public class CyclicBarrierStudy { public static void main(String[] args) throws IOException, InterruptedException { //如果將引數改為4,但是下面只加入了3個選手,這永遠等待下去 //Waits until all parties have invoked await on this barrier. CyclicBarrier barrier = new CyclicBarrier(3); ExecutorService executor = Executors.newFixedThreadPool(3); executor.submit(new Thread(new Runner(barrier, "1號選手"))); executor.submit(new Thread(new Runner(barrier, "2號選手"))); executor.submit(new Thread(new Runner(barrier, "3號選手"))); executor.shutdown(); } } class Runner implements Runnable { // 一個同步輔助類,它允許一組執行緒互相等待,直到到達某個公共屏障點 (common barrier point) private CyclicBarrier barrier; private String name; public Runner(CyclicBarrier barrier, String name) { super(); this.barrier = barrier; this.name = name; } @Override public void run() { try { Thread.sleep(1000 * (new Random()).nextInt(8)); System.out.println(name + " 準備好了..."); // barrier的await方法,在所有參與者都已經在此 barrier 上呼叫 await 方法之前,將一直等待。 barrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } System.out.println(name + " 起跑!"); } }