我有一个线程 A
,它创建一个新线程 B
。
该线程B
可以创建新线程
,它也可以创建新线程
。
我的线程 A
需要等待所有其他线程完成。
我的第一次尝试是将所有线程添加到列表中。
private List<TestcaseExecutionThread> threads = new CopyOnWriteArrayList<>();
// inside my run function
Iterator<TestcaseExecutionThread> it = threads.iterator();
while (it.hasNext()) {
TestcaseExecutionThread t = it.next();
while (t.isRunning()) {
try {
TimeUnit.MILLISECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Thread A
遍历列表中的所有元素,并仅在循环中调用一个函数,该函数返回列表中的当前线程是否仍在运行。
对于普通的 ArrayList,在第一个线程完成后,会进入死锁。
然后我使用了 CopyOnWriteArrayList,但线程 A 总是在第一个线程之后留下外部循环。
必须有一个简单的解决方案来解决该问题
最佳答案
您可以使用 Phaser
来实现这一目标。我已将逻辑包装在一个新类 MyThread
中,您应该在需要所需行为的任何地方使用它来代替 Thread
:
class MyThread extends Thread
{
MyThread(final Runnable runnable, final Phaser phaser)
{
super(() -> {
runnable.run();
phaser.arrive();
});
phaser.register();
}
}
这是示例用法。主线程创建一个线程(“A”),该线程本身创建一个线程(“B”)。主线程等待直到所有线程完成:
public static void main(String[] args)
{
final Phaser phaser = new Phaser(1);
new MyThread(
() -> {
new MyThread(() -> System.out.println("B"), phaser).start();
System.out.println("A");
try
{
Thread.sleep(1000); // wait for 1s to prove main thread is really waiting
}
catch (InterruptedException e) {}
},
phaser
).start();
phaser.arriveAndAwaitAdvance();
System.out.println("Everything is done");
}
关于Java 等待多个线程,这可能会创建新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48092591/