繁体   English   中英

如何使一个线程等待其他线程完成

[英]How to make a thread wait until other threads are completed

我有一个线程调用的函数funcA()。 此函数funcA()调用多个函数,所有这些函数均在其他并行线程上运行。 我希望我的第一个线程调用funcA()等待所有这些线程完成工作,然后移至下一行以进一步执行。

例如Thread1-> funcA();

funcA()
{
    funcBackground();   

    //Once the above method's threads have completed their work
    doSomeOtherWork(); 
}

funcBackground()
{
    Thread2 -> doJob1();
    Thread3 -> doJob2();
    Thread4 -> doJob3();
    .
    .
    .
//All the above threads have completed their work
}

我该如何实现? 我知道您可能正在考虑是否要在单个线程中全部运行,然后为什么要在funcBackground()中使用多个线程。 关键是我的funcBackground()是从多个地方调用的。 但是我只希望在应用程序中的某个位置执行此单线程。

您可以创建实现callables对象的所有线程(Thread2,thread3 ....),这些callables对象将返回Future。

并且直到所有线程都完成如下所示时,才从funcBackground退出。

    while(!future2.isDone());
    while(!future3.isDone());
    while(!future4.isDone());

或者你可以使用

future2.get()因为这也将阻塞。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM