温馨提示×

Java中的CyclicBarrier怎么使用

小亿
105
2023-08-12 02:57:01
栏目: 编程语言

在Java中,CyclicBarrier是一个同步工具,它允许一组线程等待彼此达到一个共同的屏障点,然后继续执行。下面是CyclicBarrier的使用方法:

  1. 创建CyclicBarrier对象,指定等待的线程数量和达到屏障点时需要执行的任务:
CyclicBarrier barrier = new CyclicBarrier(3, () -> {
System.out.println("All threads have reached the barrier");
});

上述代码中,我们创建了一个包含3个线程的CyclicBarrier对象,并指定当这3个线程都到达屏障点时,执行的任务是输出一条消息。

  1. 创建需要等待的线程,并在需要等待的位置调用CyclicBarrier的await()方法:
Thread thread1 = new Thread(() -> {
try {
// 线程1执行的任务
System.out.println("Thread 1 has reached the barrier");
barrier.await();
// 屏障点之后继续执行的任务
System.out.println("Thread 1 is running again");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
});
Thread thread2 = new Thread(() -> {
try {
// 线程2执行的任务
System.out.println("Thread 2 has reached the barrier");
barrier.await();
// 屏障点之后继续执行的任务
System.out.println("Thread 2 is running again");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
});
Thread thread3 = new Thread(() -> {
try {
// 线程3执行的任务
System.out.println("Thread 3 has reached the barrier");
barrier.await();
// 屏障点之后继续执行的任务
System.out.println("Thread 3 is running again");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
});
thread1.start();
thread2.start();
thread3.start();

上述代码中,我们创建了3个线程,并在每个线程的任务中分别调用了CyclicBarrier的await()方法。当3个线程都调用了await()方法后,它们将会阻塞,直到所有线程都到达屏障点。

  1. 运行代码,观察输出结果:
Thread 1 has reached the barrier
Thread 2 has reached the barrier
Thread 3 has reached the barrier
All threads have reached the barrier
Thread 1 is running again
Thread 3 is running again
Thread 2 is running again

上述输出结果显示,当3个线程都到达屏障点后,执行了屏障点后的任务,并继续执行了后续的任务。

注意事项:

  • CyclicBarrier的await()方法会抛出InterruptedException和BrokenBarrierException异常,需要进行异常处理。

  • CyclicBarrier对象可以重用,即可以在线程到达屏障点后重新使用。

0