JUC
CyclicBarrier
CyclicBarrier
循环栅栏,用来进行线程协作,等待线程满足某个计数。构造时设计【计数个数】,每个线程执行到某个需要“同步“的时刻代用await()方法进行等待,当等待的线程数满足【计数个数】时,继续执行。
相较于CountDownLatch,CyclicBarrier可以重复循环使用。
构造方法:
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
public CyclicBarrier(int parties) {
this(parties, null);
}
其中 CyclicBarrier(int parties, Runnable barrierAction)提供一个Runnable入参,用于循环计数结束后,交互回调方法。
例子:
public class CyclicBarrierTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
CyclicBarrier cyclicBarrier = new CyclicBarrier(2,()->{
log.info("task1,task2 finish...");
});
for(int i=0;i<=2;i++){
executorService.submit(()->{
log.info("task1 begin...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
cyclicBarrier.await();//计数-1 2-1=1
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
log.info("task1 ending...");
});
executorService.submit(()->{
log.info("task2 begin...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
cyclicBarrier.await();//计数减一 1-1=0
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
log.info("task2 ending...");
});
}
}
}
执行结果:
14:33:49.410 [pool-1-thread-2] INFO my.CyclicBarrierTest - task2 begin…
14:33:49.410 [pool-1-thread-1] INFO my.CyclicBarrierTest - task1 begin…
14:33:51.413 [pool-1-thread-2] INFO my.CyclicBarrierTest - task1,task2 finish…
14:33:51.414 [pool-1-thread-2] INFO my.CyclicBarrierTest - task2 ending…
14:33:51.414 [pool-1-thread-1] INFO my.CyclicBarrierTest - task1 ending…
14:33:51.414 [pool-1-thread-2] INFO my.CyclicBarrierTest - task1 begin…
14:33:51.414 [pool-1-thread-1] INFO my.CyclicBarrierTest - task2 begin…
14:33:53.415 [pool-1-thread-1] INFO my.CyclicBarrierTest - task1,task2 finish…
14:33:53.415 [pool-1-thread-1] INFO my.CyclicBarrierTest - task2 ending…
14:33:53.415 [pool-1-thread-2] INFO my.CyclicBarrierTest - task1 ending…
14:33:53.415 [pool-1-thread-1] INFO my.CyclicBarrierTest - task1 begin…
14:33:53.415 [pool-1-thread-2] INFO my.CyclicBarrierTest - task2 begin…
14:33:55.424 [pool-1-thread-2] INFO my.CyclicBarrierTest - task1,task2 finish…
14:33:55.424 [pool-1-thread-2] INFO my.CyclicBarrierTest - task2 ending…
14:33:55.424 [pool-1-thread-1] INFO my.CyclicBarrierTest - task1 ending…