我有多个子线程实例,这些实例已启动并且应继续执行,直到应用程序退出。
我有扩展任务的类,我创建线程为
new Thread(object of the class).start();
所有线程都应在主阶段关闭时终止。
primaryStage.onCloseOperation(){...}
最佳答案
我会从一开始就显式管理您的线程。特别是,在您的父类中有一个线程池,如下所示:
ExecutionService exec = Executors.newCachedExecutionService();
然后,如果您的任务旨在继续运行(而不是定期计划),那么您的任务将像这样响应中断:
while(!Thread.currentThread().isInterrupted()){
do stuff;
}
这将使任务运行直到被中断。在这种情况下,永远不要忽略 InterruptedException
,这一点很重要,因为当抛出 InterruptedException
时,会将 isInterrupted
设置为 false。当您看到 InterruptedException
时执行此操作:
}catch(InterruptedException e){
Thread.currentThread().interrupt();
return;
}
然后,您可以像这样启动子任务:
for(task : tasks){
exec.execute(task);
}
现在,当您的父任务完成时,您只需调用:
exec.shutdownNow();
停止您的子任务。如果您的子任务使用 Thread.currentThread().isInterrupted()
,则必须使用 shutdownNow()
(shutdown()
仅在以下情况下才有效)想要等待任务自行停止)。
关于java - 关闭舞台/窗口时终止所有子线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18756167/