1.简介
通俗点讲就是一组线程相互等待,直到临界点。具体可查官方文档
注意:CountDownLatch是一组线程或一个线程等待另一组线程
2.小栗子
public class CyclicBarrierDemo {
private static final int CYCLIC_BARRIER_COUNT = 2;
private static final int THREAD_COUNT = 4;
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(CYCLIC_BARRIER_COUNT, ()->{
System.out.println("达到临界点");
});
ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT);
for (int index = 0; index < THREAD_COUNT; index ++) {
executorService.execute(()->{
try {
System.out.println("ThreadId:" + Thread.currentThread().getId());
Thread.sleep(2000);
int await = cyclicBarrier.await();
System.out.println("await:" + await);
System.out.println("ThreadId:" + Thread.currentThread().getId());
} catch (Exception e) {
e.printStackTrace();
}
});
}
executorService.shutdown();
}
}
网友评论