package com.sunup.jbasis.concurrent;
import lombok.extern.slf4j.Slf4j;
import sun.rmi.runtime.Log;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
* @author lime
* <p>
* <p>
* CountDownLatch(在JDK 5中引入)是一个实用程序类,它阻止一组线程,直到某些操作完成。
* 甲CountDownLatch初始化为计数器(整数型); 当依赖线程完成执行时,此计数器递减。但是一旦计数器达到零,其他线程就会被释放。
* CyclicBarrier与CountDownLatch几乎相同,只是我们可以重用它。与CountDownLatch不同,它允许多个线程在调用最终任务之前使用await()方法(称为障碍条件)彼此等待。
*/
@Slf4j
public class CyclicBarrierTest {
public static void main(String[] args) {
new CyclicBarrierTest().start();
}
public void start() {
CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> {
log.info("all ");
});
Thread t1 = new Thread(new Task(cyclicBarrier), "T1");
Thread t2 = new Thread(new Task(cyclicBarrier), "T2");
Thread t3 = new Thread(new Task(cyclicBarrier), "T3");
if (!cyclicBarrier.isBroken()) {
t1.start();
t2.start();
t3.start();
}
}
class Task implements Runnable {
private CyclicBarrier barrier;
public Task(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Override
public void run() {
try {
log.info(Thread.currentThread().getName() + " 等候");
//等待
barrier.await();
log.info(Thread.currentThread().getName() + " 执行");
} catch (InterruptedException | BrokenBarrierException e) {
e.getStackTrace();
}
}
}
}
[T2] INFO com.sunup.jbasis.concurrent.CyclicBarrierTest - T2 等候
[T1] INFO com.sunup.jbasis.concurrent.CyclicBarrierTest - T1 等候
[T3] INFO com.sunup.jbasis.concurrent.CyclicBarrierTest - T3 等候
[T3] INFO com.sunup.jbasis.concurrent.CyclicBarrierTest - all
[T3] INFO com.sunup.jbasis.concurrent.CyclicBarrierTest - T3 执行
[T2] INFO com.sunup.jbasis.concurrent.CyclicBarrierTest - T2 执行
[T1] INFO com.sunup.jbasis.concurrent.CyclicBarrierTest - T1 执行