【问题标题】:How to make a thread wait until other threads are completed如何让一个线程等到其他线程完成
【发布时间】:2019-06-22 13:49:40
【问题描述】:

我有一个由线程调用的函数 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() 是从多个地方调用的。但我希望这个单线程只在应用程序的一个地方执行。

【问题讨论】:

  • await 关键字怎么样?异步等待我在 kotlin 中使用它
  • 我不在 kotlin。对 Android 的基于 Java 的 rxjava 有什么建议吗?

标签: android multithreading rx-java2 rx-android


【解决方案1】:

您可以创建所有执行callables 的线程(Thread2、thread3....),这将返回Futures。

在所有线程都像下面这样完成之前,不要退出funcBackground

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

或者你可以使用

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

【讨论】:

  • 你的建议是颠倒的。 OP 应该使用future2.get(),除非有充分的理由忙着等待。
猜你喜欢
  • 1970-01-01
  • 2020-09-21
  • 2010-12-26
  • 1970-01-01
  • 2021-07-11
  • 1970-01-01
  • 2021-06-21
  • 2014-10-05
  • 1970-01-01
相关资源
最近更新 更多