如何终止 ExecutorService 调用的可调用进程

How to terminate callable process called by ExecutorService

在下面的代码中我想终止ExecutorService提交的Callable进程。目前,即使在循环执行之前调用了关闭,可调用进程的执行也不会终止。

任何建议都会有所帮助。

package foundation.util.sql.parser;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.*;

public class Test {

   public static void main(String[] args) {
        try {

            final java.util.Map<String, ExecutorService> map = new HashMap<>();
            ExecutorService service = Executors.newFixedThreadPool(1);
            map.put("1", service);
Thread thread = new Thread(new Runnable() {

                @Override
                public void run() {
                    try {

                        System.out.println("Termination Initiated");
                        ExecutorService executorService = map.get("1");
                        System.out.println("ShutDown called");

                        if(!executorService.isShutdown())
                        {
                            executorService.shutdownNow();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            Future<Boolean> submit = service.submit(new Callable<Boolean>() {

                @Override
                public Boolean call() throws Exception {
                    int j = 0;
                    System.out.println(Thread.currentThread().getName());
                    for (int i=0; i<5000;i++) {
                        //Some business Process.
                        j = i;
                    }
                    System.out.println("Test____"+ j);
                    return null;
                }
            });
           thread.start();
           submit.get();
        } catch (Exception e) {
           e.printStackTrace();
        }
    }

}

当我们调用 showDownNow() 时,它不会终止 运行 任务,事实上

it just prevents waiting tasks from starting and attempts to stop currently executing tasks.

根据javadoc

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.

在您的可调用函数中,您不是responding/checking中断。您需要定期检查 interrupt flag 是否设置为 true。如果是这样,请根据需要进行必要的清理并终止。

例如,在您的情况下,您可以考虑如下检查 interrupt flag(或任何适用的地方):

for (int i=0; i<5000;i++) {
    //Some business Process.
    if(Thread.currentThread().isInterrupted()) {
     // do any cleanup and return from here.
     return false;
    }
    j = i;
}