executorservice不杀死线程

时间:2016-12-15 14:12:15

标签: java multithreading executorservice threadpoolexecutor

代码:

//List all threads:
Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
System.out.println(runningThreads.toString());

//Thread creation:
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(this);

//Thread termination:
executorService.shutdownNow();

//List all threads:
Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
System.out.println(runningThreads.toString());

我希望打印出来的列表两次都完全相同,但我得到的是打印出结果中包含的线程

如何彻底摧毁一个线程,以至于无处可寻?

1 个答案:

答案 0 :(得分:1)

shutdownNow()尝试停止正在运行的线程,但正如其API文档所述:

  

此方法不等待主动执行任务终止。使用awaitTermination来执行此操作。

因此,当调用shutdownNow()后的代码返回时,线程可能仍在运行。另请注意,您需要确保线程中运行的任务实际终止; shutdownNow()不会杀死该线程,它会尝试中断它。

正如文档所述,在调用shutdownNow()后等待线程停止后调用executorService.awaitTermination(...)