【发布时间】:2016-06-18 19:14:28
【问题描述】:
我想停止一个没有循环的线程
while(!cancelled) //where cancelled is volatile variable
{
//
}
不能使用,因为我想在没有循环的情况下执行长时间运行的任务, 如果父线程中的任何一个发生异常,如何停止子线程
@奥利弗
正如 oracle 文档中提到的那样
for (int i = 0; i < inputs.length; i++) {
heavyCrunch(inputs[i]);
if (Thread.interrupted()) {
// We've been interrupted: no more crunching.
return;
}
}
在上面的代码中 if() 只会在heavyCrunch(inputs[i]) 完成时调用
【问题讨论】:
-
Thread.interrupt应该是这样做的方式 -
@hitesh,如果你使用的是 ExecutorService,看看这个问题:stackoverflow.com/questions/37879274/…
标签: java multithreading executorservice