JDK博士说:
public class CyclicBarrier
extends Object
A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.
A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue.然后给出一个示例代码,它可以工作。
class Worker implements Runnable {
int myRow;
Worker(int row) { myRow = row; }
public void run() {
while (!done()) {
processRow(myRow);
try {
barrier.await();
} catch (InterruptedException ex) {
...
class Solver
...
List<Thread> threads = new ArrayList<Thread>(N);
for (int i = 0; i < N; i++) {
Thread thread = new Thread(new Worker(i));
threads.add(thread);
thread.start();
}
// wait until done
for (Thread thread : threads)
thread.join(); // here we still need to wait all threads using join()
...但是CyclicBarrier在我看来仍然是多余的:线程“互相等待”,这是由调用thread.join()的for循环完成的。
无论如何,只要我希望收集线程的所有结果,我就必须等待它们完成,对吗?如果Thread.join()有效,那么为什么或者在什么情况下我们需要引入CyclicBarrier(OCAM剃刀?)
发布于 2022-06-18 05:14:30
从用于线程的Javadoc打电话给join()
等待这个线程死掉。
如果您有一些线程比“开始”和“完成”更有趣,那么您也许可以使用join()来等待它们全部完成。
CyclicBarriers在涉及固定大小线程的程序中非常有用,这些线程必须偶尔等待对方。
在许多场景中,您希望在线程本身之间定义更有趣或更依赖的交互,而“等待线程死亡”的场景不能提供足够的控制。
java.util.concurrent包中还有许多其他有用的东西,如相位器和CountDownLatch。因此,您可能不需要任何这些(目前),但它们可能非常有用。
https://stackoverflow.com/questions/72666297
复制相似问题