[英]Active thread count doesn't decrements even after the thread closes
在下面的代碼中,即使執行程序中的線程在 5 秒后終止,Thread.activeCount() 也始終返回 2。
public class MainLoop {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(12);
executor.submit(new Callable<Void>() {
public Void call() throws Exception {
Thread.sleep(5000);
return null;
}
});
while (true) {
System.out.println(Thread.activeCount());
Thread.sleep(1000);
}
}
}
我希望 Thread.activeCount() 在 5 秒后返回 1。 為什么總是返回 2 ?
請參閱newFixedThreadPool的文檔。 https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)
在任何時候,最多nThreads個線程都是活動的處理任務。 池中的線程將一直存在,直到明確將其關閉。
將可調用對象提交給此執行程序后,它將被池中的線程之一處理並對其進行處理。 完成此執行后,線程將在池中處於空閑狀態,等待下一個可調用。
您應該使用service.shutdown()
關閉executorService,否則它將繼續分配資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.