CyclicBarrier是一個同步輔助類,它允許一組線程在達到某個屏障點之前彼此互相等待。在Java中,可以通過以下步驟來使用CyclicBarrier:
CyclicBarrier barrier = new CyclicBarrier(3, () -> {
System.out.println("All threads have reached the barrier");
});
Thread t1 = new Thread(() -> {
try {
System.out.println("Thread 1 is waiting at the barrier");
barrier.await();
System.out.println("Thread 1 has passed the barrier");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
});
t1.start();
Thread t2 = new Thread(() -> {
try {
System.out.println("Thread 2 is waiting at the barrier");
barrier.await();
System.out.println("Thread 2 has passed the barrier");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
});
t2.start();
通過以上步驟,可以實現多個線程在達到某個屏障點后進行同步操作。需要注意的是,CyclicBarrier只能被重置一次,之后需要重新創建新的CyclicBarrier對象。