需要一组线程同时达到某个条件后一起啊开始执行。
类似的场景:一个线程代表一个跑步运动员,当所有的运动员都准备好了之后才一起出发。只要有一个没有准备好,大家都继续等待。
package com.lihuan.concurrentUtil;
import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CyclicBarrierTest {
static class MyRunnable implements Runnable{
private CyclicBarrier barrier;
private String name;
public MyRunnable(CyclicBarrier barrier, String name) {
this.barrier = barrier;
this.name = name;
}
@Override
public void run() {
try {
Thread.sleep(1000*(new Random().nextInt(5)));
System.out.println(name+"准备OK");
//每个线程执行await()开始等待
barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(name+"GO!!!");
}
}
public static void main(String[] args) {
//创建CyclicBarrier 设置屏障数为3
CyclicBarrier barrier = new CyclicBarrier(3);
/**
* 创建固定数量的线程池
* 添加三个线程
* 每个线程执行await()开始等待
* 当三个线程都调用await()时开始,一起开始执行
*/
ExecutorService pool = Executors.newFixedThreadPool(3);
pool.execute(new Thread(new MyRunnable(barrier, "zhangsan")));
pool.execute(new Thread(new MyRunnable(barrier, "lisi")));
pool.execute(new Thread(new MyRunnable(barrier, "wangwu")));
pool.shutdown();
}
}
结果