定义countdownlatch: a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
cyclicbarrier: a synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.
上述是oracle官方定义。简单来说
countdownlatch:计数器,允许一个或多个线程等待,直到在其他线程中执行的一组操作完成。
cyclicbarrier:循环屏障,它允许一组线程相互等待以达到一个共同的屏障点。
区别
countdownlatch 是 aqs (abstractqueuedsynchronizer) 的一员,但 cyclicbarrier 不是。
countdownlatch 的使用场景中,有两类线程,一类是调用await()方法的等待线程,另一类是调用countdownl() 方法的操作线程。在 cyclicbarrier 的情境中,所有线程都是等待彼此的线程,属于同一类型。
countdownlatch 是减计数,递减完后不能复位,cyclicbarrier 是加计数,递增完后自动复位
countdownlatch 示例创建两组线程,一组等待另一组执行完才继续进行
countdownlatch countdownlatch = new countdownlatch(5);executorservice executorservice = executors.newcachedthreadpool();for (int i = 0; i < 5; i++) { executorservice.execute(() -> { countdownlatch.countdown(); system.out.println("run.."); });}for (int i = 0; i < 3; i++) { //我们要等上面执行完成才继续 executorservice.execute(() -> { try { countdownlatch.await(); } catch (interruptedexception e) { e.printstacktrace(); } system.out.println("await.."); });}executorservice.shutdown();
打印:
run..
run..
run..
run..
run..
await..
await..
await..
等待累加线程执行完,主线程再输出累加结果
public class threadunsafeexample { private int cnt = 0; public void add() { cnt++; } public int get() { return cnt; } public static void main(string[] args) throws interruptedexception { final int threadsize = 1000; threadunsafeexample example = new threadunsafeexample(); final countdownlatch countdownlatch = new countdownlatch(threadsize); executorservice executorservice = executors.newcachedthreadpool(); for (int i = 0; i < threadsize; i++) { executorservice.execute(() -> { example.add(); countdownlatch.countdown(); }); } countdownlatch.await(); executorservice.shutdown(); system.out.println(example.get()); }}
打印:
997
3 模拟并发
executorservice executorservice = executors.newcachedthreadpool(); countdownlatch countdownlatch = new countdownlatch(1); for (int i = 0; i < 5; i++) { executorservice.submit( () -> { try { countdownlatch.await(); system.out.println("【" + thread.currentthread().getname() + "】开始执行……"); } catch (interruptedexception e) { e.printstacktrace(); } }); } thread.sleep(2000); countdownlatch.countdown();//开始并发 executorservice.shutdown();
打印:
【pool-2-thread-2】开始执行……
【pool-2-thread-5】开始执行……
【pool-2-thread-3】开始执行……
【pool-2-thread-1】开始执行……
【pool-2-thread-4】开始执行……
cyclicbarrier 示例所有线程相互等待,直到某一步完成后再继续执行
final int totalthread = 3; cyclicbarrier cyclicbarrier = new cyclicbarrier(3); executorservice executorservice = executors.newcachedthreadpool(); for (int i = 0; i < totalthread; i++) { executorservice.execute(() -> { system.out.println("before.."); try { cyclicbarrier.await(); } catch (interruptedexception | brokenbarrierexception e) { e.printstacktrace(); } system.out.println("after.."); }); } executorservice.shutdown();
打印:
before..
before..
before..
after..
after..
after..
以上就是java countdownlatch计数器与cyclicbarrier循环屏障怎么定义的详细内容。