請幫我看下面代碼中線程泄漏的原因。即使在run()完成後(從安慰的打印語句驗證)並且主方法已退出(從打印語句和分析器工具驗證),TestThread
也不會收集垃圾回收。爲什麼運行ScheduleExecutorService的UserThread不會被垃圾收集
但是,如果TestThread
設置爲守護程序線程,即t.setDaemon(true)
,則會收集垃圾回收。下面的代碼只是一個示例代碼,它說明了我的應用程序中的問題。我正在嘗試使用一些預先存在的日程安排類(由其他人使用ScheduledExecutorService
設計)。我注意到,當我保持與類的多個Runnable
s時,創建的線程永遠不會收集垃圾。
public class ThreadTest {
static void runThreadWithExecutor() {
final String name = "TestThread";
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor(
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, name);
t.setDaemon(false);
return t;
}
});
ses.schedule(new Runnable() {
@Override
public void run() {
System.out.println("entered " + name);
System.out.println("exiting " + name);
}},
2,
TimeUnit.SECONDS);
}
public static void main(String[] args) throws InterruptedException {
System.out.println("entered main");
runThreadWithExecutor();
Thread.sleep(5000);
System.out.println("exiting main");
}
}
好信息約翰。一個調整。 'shutdown()'不會結束線程池中的所有線程,直到所有作業已提交完成。 – Gray
@格雷好點 –
謝謝你們。雖然我最初選擇這個作爲我接受的答案,但後來我選擇了格雷的答案,因爲如果沒有格雷的答案,這個答案就不言自明。但是,這個迴應給了我充分的解釋,需要有信心修改代碼:)並且它可以工作! – Kes115