Refer to: http://my.oschina.net/redhouse/blog/60739
CyclicBarrier (周期障碍)类可以帮助同步,它允许一组线程等待整个线程组到达公共屏障点。CyclicBarrier 是使用整型变量构造的,其确定组中的线程数。当一个线程到达屏障时(通过调用 CyclicBarrier.await()),它会被阻塞,直到所有线程都到达屏障,然后在该点允许所有线程继续执行。与CountDownLatch不同的是,CyclicBarrier 所有公共线程都到达后,可以继续执行下一个目标点,而CountDownLatch第一次到达指定点后,也就是记数器减制零,就无法再次执行下一目标工作。下面主要演义CyclicBarrier 的用法:
package com.test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestCyclicBarrier {
private static int[] timeWalk = { 5, 8, 15, 15, 10 }; // 徒步需要的时间
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: 徒步 上海
徒步飞机 合肥
自驾飞机 合肥
大巴飞机 合肥
-----------------------------------------------------
Silence, the way to avoid many problems;
Smile, the way to solve many problems;