我正在试着看看是否有可能shutdownNow()一个仍在执行任务的ExecutorService。
public static void main (String []args) throws InterruptedException
{
ExecutorService exSer = Executors.newFixedThreadPool(4);
List<ExecutorThing> lista = new ArrayList<>();
lista.add(new ExecutorThing());
lista.add(new ExecutorThing());
lista.add(new ExecutorThing());
lista.add(new ExecutorThing());
lista.add(new ExecutorThing());
List<Future<Object>> futureList = exSer.invokeAll(lista);
exSer.shutdownNow();ExecutorThing类如下所示:
public class ExecutorThing implements Callable<Object>{
public Object call() {
while (!(Thread.currentThread().isInterrupted()))
for (int i=0;i<1;i++)
{
System.out.println(Thread.currentThread().getName());
}
return null;
}
}我想知道为什么即使我检查了中断标志.shutdownNow应该通过interrupt()终止任务。
我哪里错了?
提前谢谢。
PS在this问题中,他们提供的解决方案和我使用的一样,但对我来说不管用。也许是因为我用了invokeAll?
提前谢谢。
发布于 2013-07-24 16:27:41
答案很简单,您只需仔细阅读invokeAll的Javadoc
执行给定的任务,返回保存其状态的期货列表,并在所有任务完成后返回结果。
(强调我的)。
换句话说,您的shutdownNow永远不会被执行。我把你的代码改为:
public class Test {
public static void main (String []args) throws InterruptedException
{
ExecutorService exSer = Executors.newFixedThreadPool(4);
exSer.submit(new ExecutorThing());
exSer.submit(new ExecutorThing());
exSer.submit(new ExecutorThing());
exSer.submit(new ExecutorThing());
exSer.shutdownNow();
}
}
class ExecutorThing implements Callable<Object> {
public Object call() throws InterruptedException {
while (!(currentThread().isInterrupted()))
System.out.println(currentThread().isInterrupted());
return null;
}
}毫不奇怪,现在它的行为就像你期望的那样。
https://stackoverflow.com/questions/17839339
复制相似问题