CyclicBarrier (週期障礙)類能夠幫助同步,它容許一組線程等待整個線程組到達公共屏障點。CyclicBarrier 是使用整型變量構造的,其肯定組中的線程數。當一個線程到達屏障時(經過調用 CyclicBarrier.await()),它會被阻塞,直到全部線程都到達屏障,而後在該點容許全部線程繼續執行。與CountDownLatch不一樣的是,CyclicBarrier 全部公共線程都到達後,能夠繼續執行下一個目標點,而CountDownLatch第一次到達指定點後,也就是記數器減制零,就沒法再次執行下一目標工做。下面主要演義CyclicBarrier 的用法:java
package com.test;this
import java.text.SimpleDateFormat;spa
import java.util.Date;線程
import java.util.concurrent.BrokenBarrierException;orm
import java.util.concurrent.CyclicBarrier;同步
import java.util.concurrent.ExecutorService;it
import java.util.concurrent.Executors;io
public class TestCyclicBarrier {form
private static int[] timeWalk = { 5, 8, 15, 15, 10 }; // 徒步須要的時間class
private static int[] timeSelf = { 1, 3, 4, 4, 5 }; // 自駕遊
private static int[] timeBus = { 2, 4, 6, 6, 7 }; // 旅遊大巴
static String now() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(new Date()) + ": ";
}
static class Tour implements Runnable {
private int[] times;
private CyclicBarrier barrier;
private String tourName;
public Tour(CyclicBarrier barrier, String tourName, int[] times) {
this.times = times;
this.tourName = tourName;
this.barrier = barrier;
}
public void run() {
try {
Thread.sleep(times[0] * 1000);
System.out.println(now() + tourName + " 合肥");
barrier.await();
Thread.sleep(times[1] * 1000);
System.out.println(now() + tourName + " 南京");
barrier.await();
Thread.sleep(times[4] * 1000);
System.out.println(now() + tourName + " 上海");
barrier.await();
System.out.println(tourName + "飛機 合肥");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(3);
ExecutorService exec = Executors.newFixedThreadPool(3);
exec.submit(new Tour(barrier, "徒步", timeWalk));
exec.submit(new Tour(barrier, "自駕", timeSelf));
exec.submit(new Tour(barrier, "大巴", timeBus));
exec.shutdown();
}
}
最後執行結果以下:
16:24:35: 自駕 合肥
16:24:36: 大巴 合肥
16:24:39: 徒步 合肥
16:24:42: 自駕 南京
16:24:43: 大巴 南京
16:24:47: 徒步 南京
16:24:52: 自駕 上海
16:24:54: 大巴 上海
16:24:57: 徒步 上海
徒步飛機 合肥
自駕飛機 合肥
大巴飛機 合肥