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是一次性的,到達指定數量后,所有線程都會釋放,但不能再次使用。