package demo;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CyclicBarrierTest {
public static void main(String[] args)throws InterruptedException,IOException{
//创建一个CyclicBarrier类型的同步器,给定3个线程相互等待,知道到达某个屏障点
CyclicBarrier barrier =new CyclicBarrier(3);
//创建一个线程池并且启动三个线程
ExecutorService execPool=Executors.newFixedThreadPool(3);
execPool.submit(new Thread(new Person(barrier,"张三")));
execPool.submit(new Thread(new Person(barrier,"李四")));
execPool.submit(new Thread(new Person(barrier,"王五")));
execPool.shutdown();
}
}
class Person implements Runnable{
private CyclicBarrier barrier;
private String name;
public Person(CyclicBarrier barrier,String name){
super();
this.barrier=barrier;
this.name=name;
}
@Override
public void run() {
try {
Thread.sleep(1000*(new Random().nextInt(10)));
System.out.println(name+"准备好了");
//在此处设置一个公共的屏障点,当三个线程都“准备”好后再继续向后执行;否则将一直等待;
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println(name+"起跑");
}
}
运行结果;
王五准备好了
。。。
李四准备好了
。。。
张三准备好了
。。。
张三起跑
王五起跑
李四起跑