java - executorService 接口(interface)的 ShutdownNow 不会关闭正在进行的任务

标签 java multithreading concurrency executorservice shutdown

在第一个进程从 invokeAny 方法提供一些输出后,我立即使用 shutdownNow 关闭进程。但在输出中,即使在调用 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 链接

类:ExecutorServiceThreeTypesOfShutDownMethodMainClass

包:com.Concurrency.JavaSEConcurrencyAPIStudyProject.HighLevelApis.ExecutorServiceInterface

要使用的项目:JavaSEConcurrencyAPIStudyProject

git链接:Git link for project for more details

请帮忙,为什么会出现这种情况?我该如何解决这个问题?

最佳答案

该方法的 Javadoc 内容如下:

除了尽最大努力尝试停止处理主动执行的任务之外,没有任何保证。例如,典型的实现将通过 Thread.interrupt() 取消,因此任何无法响应中断的任务可能永远不会终止。

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

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

关于java - executorService 接口(interface)的 ShutdownNow 不会关闭正在进行的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61308952/

相关文章:

java - 非法转义字符后跟空格

java - Android ndk 中的共享内存

linux - Lazarus Linux Ubuntu 上的线程

java - 处理 Java 套接字并发

asp.net - ASP.NET并发

Java执行路径名中带空格的命令

java - 如果值为哈希符号(#),如何获取请求参数值

multithreading - EndDialog 不能在线程中调用?

multithreading - 为什么在调用Clojure中的Future时仅运行32个线程?

android - 如何减少 Android 中的 Thread.sleep() 延迟