CyclicBarrier是Java中的一个同步辅助类,它可用于让一组线程在某个条件达成时互相等待,然后同时继续执行。它的用法如下:
下面是一个简单的示例,演示了CyclicBarrier的用法:
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierExample {
public static void main(String[] args) {
final int numThreads = 3;
CyclicBarrier barrier = new CyclicBarrier(numThreads, () -> {
System.out.println("All threads have reached the barrier");
});
for (int i = 0; i < numThreads; i++) {
Thread thread = new Thread(new Worker(barrier));
thread.start();
}
}
static class Worker implements Runnable {
private final CyclicBarrier barrier;
public Worker(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " is waiting at the barrier");
barrier.await();
System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
运行上述代码,会创建3个线程,在屏障点处等待,当所有线程都到达屏障点时,所有线程会继续执行,并输出相应的信息。
注意:CyclicBarrier与CountDownLatch的区别在于,CyclicBarrier在达到屏障点时,所有线程会被释放并继续执行,而CountDownLatch是一次性的,到达指定数量后,所有线程都会释放,但不能再次使用。