JUC 即 java.util.concurrent 包,提供了大量的工具类来简化并发编程。
CyclicBarrier 栅栏(zha lan),是一种线程同步器,基于AQS,用于多个线程的循环集结,在业务场景中可以用于限流、或者游戏开房的配对。
1 CyclicBarrier使用方法示例
其构造方法表示,当线程开始等待时,如果等待数量达到预定数量parties,就会执行barrierAction。
/**
when the given number of parties (threads) are waiting upon it, and which will execute the given barrier action when the barrier is tripped, performed by the last thread entering the barrier.
*/
public CyclicBarrier(int parties, Runnable barrierAction)
下面的例子中,有100个线程任务,每当有5个线程await等待时既满足“栅栏”的预订人数,于是发车。
public class CyclicBarrierTest {
public static void main(String[] args) throws InterruptedException {
CyclicBarrier barrier = new CyclicBarrier(5, new Runnable() {
@Override
public void run() {
System.out.println("满人发车.");
}
});
for(int i=0;i<100;i++) {
Thread.sleep(new Random().nextInt(1000));
new Thread(()->{
try {
//做一些业务逻辑
System.out.println(Thread.currentThread().getName() +" 满足条件");
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
运行结果:
总结
CyclicBarrier当等待线程达到预定数量即出发预定的行为。 适用于限流、配对等业务场景。
多线程系列在github上有一个开源项目,主要是本系列博客的实验代码。
https://github.com/forestnlp/concurrentlab
如果您对软件开发、机器学习、深度学习有兴趣请关注本博客,将持续推出Java、软件架构、深度学习相关专栏。
您的支持是对我最大的鼓励。