我正在尝试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?
提前致谢。
答案 0 :(得分:2)
答案很简单,你只需仔细阅读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;
}
}
毫不奇怪,现在它的行为与您期望的一样。