[英]Why joining all threads in one loop is different from starting and joining one thread at a time?
[英]Loop not terminating when joining on all other threads
首先,我永遠搜索答案。 我一直試圖以這種方式加入我所有的線程:
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();
}
和我得到相同的結果。 幫助將不勝感激:)
您正在等待屬於JVM的線程死亡,但是您錯誤地指定了邏輯。 所有線程都將符合“不包含main或不包含system”的條件,除非它以某種方式包含了兩個單詞。 嘗試使用&&
代替:
if(!t.toString().contains("main") && !t.toString().contains("system"))
使用&&
,我的過程很快就存在了。
如果您正在等待線程死亡,請維護自己的程序啟動線程列表,然后等待線程死亡。 不要從Thread.getAllStackTraces
獲取列表,因為它會包含其他您尚未啟動並且不會首先死亡的線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.