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对象。