java 多執行緒全部結束判斷方法

2021-07-29 22:04:32 字數 865 閱讀 7335

1.join()

如果是乙個執行緒,可以使用此方法,多個不合適

2.countdownlatch

此為併發計數器,每個執行緒結束後減一(countdown()),countdownlatch.await();//等待所有子執行緒執行完

public class importthread extends thread  

@override  

public void run()  

}countdownlatch threadsignal = new countdownlatch(threadnum);//初始化countdown  

for (int ii = 0; ii < threadnum; ii++)  

threadsignal.await();//等待所有子執行緒執行完  

system.out.println(thread.currentthread().getname() + "結束.");//列印結束標記 

3.執行緒池threadpoolexecutor的shutdown與awaittermination方法

executor.shutdown();//只是不能再提交新任務,等待執行的任務不受影響  

try while(loop);  

} catch (interruptedexception e)  

//或者

exe.shutdown();  

system.out.println("shutdown():啟動一次順序關閉,執行以前提交的任務,但不接受新任務。");  

while(true)  

thread.sleep(1000);    

}  

多執行緒如何判斷全部執行緒是否已經全部結束?

提問者 旺旺 瀏覽次數 1904次 class readfilethread implements runnable public void readfilethread int i catch exception e public void run catch exception e public...

判斷執行緒是否全部結束

第一種 使用executorservice.isterminated executorservice cachedthreadpool executors.newcachedthreadpool cachedthreadpool submit new callable cachedthreadpoo...

Java 結束執行緒

public class threadex implements runnable public void stop 上面這種方法當啟動執行緒後在關閉時需要手動呼叫stop方法關閉執行緒,如果程式中只有乙個執行緒後台執行,那麼可以採用以下方式保證程式重新啟動時,正確關閉上一次開啟的後台執行緒,避免記...