[英]ScheduledExecutorService does not end thread like Timer
我有2個代碼段,一個使用ScheduledExecutorService在特定時間執行線程,另一個使用Timer在特定時間執行TimerTask。 問題是在使用ScheduledExecutorService時,即使線程的run()到達末尾,監視程序仍指示它仍處於活動狀態(請參見下面的圖像)。 另一方面,TimerTask在執行完成后結束其線程。
我已經將ScheduledExecutorService的Thread更改為TimerTask,但是收到了相同的結果。 使用ScheduledExecutorService時如何解決此問題?
計時器:
TimerTask task = new TimerTask()
{
@Override
public void run()
{
System.out.println("doing something");
}
};
Timer t = new Timer();
t.schedule(task, 250);
ScheduledExecutorService的:
Thread task = new Thread()
{
@Override
public void run()
{
System.out.println("doing something");
}
};
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.schedule(task, 250, TimeUnit.MILLISECONDS);
在第二個片段中,您創建了一個Thread
實例,但是ScheduledExecutorService
將該實例用作Runnable
,即。 它只關心其run
方法。 它實際上並沒有start
Thread
。
ScheduledExecutorService
維護自己的Thread
來執行任務。 使用newSingleThreadScheduledExecutor
,這是一個非守護Thread
。 您需要shutdown
ScheduledExecutorService
才能完成該Thread
。
在最后一個對
Timer
對象的實時引用消失並且所有未完成的任務均已完成執行之后,計時器的任務執行線程會正常終止(並受到垃圾回收的影響)。
執行完TimerTask
,它將完成其內部線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.