在连接所有其他线程时循环不终止

时间:2014-08-06 23:07:13

标签: java multithreading

首先,我永远搜索了答案。 我一直试图以这种方式加入我的所有主题:

Set<Thread> threads = Thread.getAllStackTraces().keySet();
try {
    for (Thread t : threads)
    if(t!=Thread.currentThread())
        t.join(5*1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

但是我陷入无限循环?我可以看到线程在我调试时结束了所以它是什么?

我也尝试过:

Set<Thread> threads = Thread.getAllStackTraces().keySet();
try {
    for (Thread t : threads)
    if(!t.toString().contains("main") || !t.toString().contains("system"))
        t.join(5*1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

我得到了相同的结果。帮助将不胜感激:))

1 个答案:

答案 0 :(得分:1)

您正在等待作为JVM一部分的线程死亡,但您错误地指定了您的逻辑。所有线程都符合条件“不包含main或不包含系统”,除非它以某种方式包含两个单词。请尝试使用&&

if(!t.toString().contains("main") && !t.toString().contains("system"))

使用&&,我的流程很快就存在。

如果你正在等待线程死掉,那么维护你自己的程序启动的线程列表,并等待它们死掉。不要从Thread.getAllStackTraces获取列表,因为它将包含您未启动但不会先死的其他线程。

相关问题