首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >关于shutdownNow of ExecutorService

关于shutdownNow of ExecutorService
EN

Stack Overflow用户
提问于 2013-07-24 16:07:41
回答 1查看 161关注 0票数 1

我正在试着看看是否有可能shutdownNow()一个仍在执行任务的ExecutorService。

代码语言:javascript
复制
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类如下所示:

代码语言:javascript
复制
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?

提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-24 16:27:41

答案很简单,您只需仔细阅读invokeAll的Javadoc

执行给定的任务,返回保存其状态的期货列表,并在所有任务完成后返回结果

(强调我的)。

换句话说,您的shutdownNow永远不会被执行。我把你的代码改为:

代码语言:javascript
复制
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;
  }
}

毫不奇怪,现在它的行为就像你期望的那样。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17839339

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档