1

I am working on building an API for an application that already exists, which sometimes uses threads. So one on my methods is like this

private SSG theSSG;
...
private void doSomething(){
  theSSG.loadMenu();

//my code
}

Now, the loadMenu method could give birth to a thread, but not necessarily. If it does, doSomething will execute the rest of the code, while the new thread is executing other code. What I need is a way to wait for the loadMenu() to finish executing all of its children threads before perceeding to the next line of code. I do not have a reference of the thread that could possibly run, since that is based on the user's choice, so I can't use join(). I also can't edit the application (or what happens in loadMenu).

4

1 回答 1

2

除非您引用了 Thread 对象1,否则无法判断线程是否已完成。

(理论上)可以遍历 JVM 中所有现有的 Thread 对象,并尝试识别可能与任务相关联的线程(按名称) 。但是我不知道在没有帮助的情况下,您如何可靠地区分线程,而无需了解它们是什么。如果你能得到这样的帮助,那就是向孩子索取参考资料的一小步。

最好的办法是重新设计应用程序的这一部分。要么改变一些东西,以便框架知道(或可以找出)子线程是什么,要么它可以将“等待线程完成”功能委托给可以实现它的东西。


1 - 有一个(无用的)例外。你总是可以通过调用找到“这个线程” Thread.currentThread()。但是,保证当前线程仍然活着。如果你(错误地)试图给自己一个线程join(),坏事就会发生;例如,线程将死锁。

于 2014-10-26T06:21:41.103 回答