CyclicBarrier循环栅栏
文章目录
1.概念
CountDownLatch
不能重用,每次循环必须创建新的对象.
CyclicBarrier 循环栅栏
,用来进行线程协作,等待线程满足某个计数。
构造时设置『计数个数』,每个线程执行到某个需要“同步”的时刻调用 await() 方法进行等待,当等待的线程数满足『计数个数』时,继续执行 .
CyclicBarrier 与 CountDownLatch 的主要区别在于 CyclicBarrier 是可以重用的 CyclicBarrier 可以被比喻为『人满发车』
1.CyclicBarrier基本用法
package com.concurrent.p10;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Slf4j(topic = "c.Test_CyclicBarrier")
public class Test_CyclicBarrier {
public void sleep(long mills) {
try {
Thread.sleep(mills);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 输出:
*16:24:52.761 [pool-1-thread-2] DEBUG c.Test_CyclicBarrier - task2 stat...
* 16:24:52.761 [pool-1-thread-1] DEBUG c.Test_CyclicBarrier - task1 stat...
* 16:24:55.766 [pool-1-thread-2] DEBUG c.Test_CyclicBarrier - task1,task2 finish...
* 16:24:55.766 [pool-1-thread-2] DEBUG c.Test_CyclicBarrier - task2 end...
* 16:24:55.766 [pool-1-thread-1] DEBUG c.Test_CyclicBarrier - task1 end...
* 16:24:55.766 [pool-1-thread-1] DEBUG c.Test_CyclicBarrier - task2 stat...
* 16:24:55.766 [pool-1-thread-2] DEBUG c.Test_CyclicBarrier - task1 stat...
* 16:24:58.766 [pool-1-thread-1] DEBUG c.Test_CyclicBarrier - task1,task2 finish...
* 16:24:58.766 [pool-1-thread-2] DEBUG c.Test_CyclicBarrier - task1 end...
* 16:24:58.766 [pool-1-thread-2] DEBUG c.Test_CyclicBarrier - task1 stat...
* 16:24:58.766 [pool-1-thread-1] DEBUG c.Test_CyclicBarrier - task2 end...
* 16:24:58.766 [pool-1-thread-1] DEBUG c.Test_CyclicBarrier - task2 stat...
* 16:25:01.766 [pool-1-thread-1] DEBUG c.Test_CyclicBarrier - task1,task2 finish...
* 16:25:01.766 [pool-1-thread-2] DEBUG c.Test_CyclicBarrier - task1 end...
* 16:25:01.766 [pool-1-thread-1] DEBUG c.Test_CyclicBarrier - task2 end...
*/
@Test
public void test1() {
//创建线程池
ExecutorService service = Executors.newFixedThreadPool(2);
//创建CyclicBarrier
CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
log.debug("task1,task2 finish...");
});
for (int i = 0; i < 3; i++) {
service.submit(() -> {
log.debug("task1 stat...");
sleep(2000);
try {
cyclicBarrier.await(); //2-1=1
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
log.debug("task1 end...");
});
service.submit(() -> {
log.debug("task2 stat...");
sleep(3000);
try {
cyclicBarrier.await(); //1-1=0
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
log.debug("task2 end...");
});
}
service.shutdown();
for (; ; ) ;
}
}