CyclicBarrier 类,就像一个哨子,等所有人都准备好了之后,一声令下,全部开始跑。
区别于 CountDownLatch ,CountDownLatch 是阻塞主线程,等其他的线程执行完了之后才让主线程继续执行。CyclicBarrier是阻塞子线程,等所有的子线程准备好了之后,才让所有的子线程全部开始执行
具体用法:
1.实例化 final CyclicBarrier barrier = new CyclicBarrier(3);
2.将 barrier 传入 线程中,调用 barrier.await(); 方法,如果 new CyclicBarrier的时候 参数给的 3,那么,barrier.await();必须调用三次之后线程才会全部开始执行。
示例代码:
import java.util.concurrent.*;
public class Main3 {
static class Runner implements Runnable{
private CyclicBarrier barrier;
private String name;
public Runner(CyclicBarrier barrier, String name) {
this.barrier = barrier;
this.name = name;
}
@Override
public void run() {
try {
System.out.println( "运动员【"+ this.name +"】开始准备" );
Thread.sleep(3000);
System.out.println("运动员【"+ this.name +"】开始准备完成..." );
barrier.await();
System.out.println( "运动员【"+ this.name +"】Go!!!" );
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
final CyclicBarrier barrier = new CyclicBarrier(3);
ExecutorService pool = new ThreadPoolExecutor(3,3,0, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
pool.submit(new Runner(barrier, "zhangzq"));
pool.submit(new Runner(barrier, "licm"));
pool.submit(new Runner(barrier, "youy"));
pool.shutdown();
}
}