executorService接口的ShutdownNow不会关闭正在执行的任务

问题描述 投票:0回答:1

我已经使用shutdownNow在第一个进程从invokeAny方法提供了一些输出之后立即关闭了进程。但是在输出中,即使调用shutDownNow(),我也可以看到进程正在完成并完成其工作,然后才关闭。代码:

int numberOfRecordsInsertedSuccessfully = 0;
    List<String> userRecordList = readFile(
            "C:\\Users\\sonar\\git\\MultiThreading-Cocurrency\\JavaSEConcurrencyAPIStudyProject\\src\\main\\java\\Resources\\ExecutorServiceUserFile.txt");
    // ExecutorService executorService = Executors.newSingleThreadExecutor();  //Thread pool of single thread.
    // ExecutorService executorService = Executors.newFixedThreadPool(3); //Thread pool size is 3 here
    ExecutorService executorService = Executors.newCachedThreadPool();
    UserDao userDao = new UserDao();

    List<Callable<Integer>> listOfCallable= new ArrayList<>();
    userRecordList.forEach(x -> listOfCallable.add(new UserProcessor(x, userDao)));

    try {
        Integer future = executorService.invokeAny(listOfCallable);
        System.out.println(future);
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    System.out.println(executorService.shutdownNow());
    System.out.println("ExecutorService is shutting down " + executorService.isShutdown()); //After getting first future result this statement will be executed.
    System.out.println("ExecutorService is Terminated " + executorService.isTerminated());

控制台上的输出是:enter image description here

有关代码的更多详细信息,请参考上面的git链接与

class:ExecutorServiceThreeTypesOfShutDownMethodMainClass

程序包:com.Concurrency.JavaSEConcurrencyAPIStudyProject.HighLevelApis.ExecutorServiceInterface

要使用的项目:JavaSEConcurrencyAPIStudyProject

git链接:Git link for project for more details

请帮助,为什么会这样?我该如何解决这个问题?

java multithreading concurrency executorservice shutdown
1个回答
0
投票

该方法的Javadoc表示以下内容:

除了尽力而为后,无法保证停止处理正在执行的任务。例如,典型的实现将通过Thread.interrupt()取消,因此任何无法响应中断的任务都可能永远不会终止。

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html

因此,如果您的任务不检查中断的标志并捕获并忽略InterruptedException,那么shutdownNow()将无法停止它们

© www.soinside.com 2019 - 2024. All rights reserved.