Java 关于ExecutorNow服务的关闭

Java 关于ExecutorNow服务的关闭,java,interrupt,executorservice,callable,Java,Interrupt,Executorservice,Callable,我正在尝试查看是否可以shutdownNow()一个仍在执行任务的ExecutorService public static void main (String []args) throws InterruptedException { ExecutorService exSer = Executors.newFixedThreadPool(4); List<ExecutorThing> lista = new ArrayList<>(); lista

我正在尝试查看是否可以
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();
publicstaticvoidmain(String[]args)抛出InterruptedException
{
ExecutorService exSer=Executors.newFixedThreadPool(4);
List lista=new ArrayList();
添加(newexecutorThing());
添加(newexecutorThing());
添加(newexecutorThing());
添加(newexecutorThing());
添加(newexecutorThing());
List futureList=exSer.invokeAll(lista);
exSer.shutdownNow();
下面是一个例子:

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;
        }
}
公共类ExecutorThing实现可调用{
公共对象调用(){
而(!(Thread.currentThread().isInterrupted())

对于(inti=0;i来说,答案非常简单,您只需仔细阅读
invokeAll的Javadoc即可:

执行给定的任务,当所有任务完成时,返回保存其状态和结果的未来列表。

(我的重点)

换句话说,您的
关机现在
永远不会执行。我将您的代码更改为:

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;
  }
}
公共类测试{
公共静态void main(字符串[]args)引发InterruptedException
{
ExecutorService exSer=Executors.newFixedThreadPool(4);
exSer.submit(new ExecutorThing());
exSer.submit(new ExecutorThing());
exSer.submit(new ExecutorThing());
exSer.submit(new ExecutorThing());
exSer.shutdownNow();
}
}
类ExecutorThing实现可调用{
公共对象调用()引发InterruptedException{
而(!(currentThread().isInterrupted())
System.out.println(currentThread().isInterrupted());
返回null;
}
}
毫不奇怪,现在它的行为与您期望的一样