如何强制立即终止 ThreadPoolExecutor 中的所有 worker

我在.我的接口上有一个停止按钮,应该立即终止里面的所有线程。我正在寻找一种方法来做到这一点。(不带 或 )。TheadPoolExecutorThreadPoolExecutorshutDown()shutDownNow()

谢谢


答案 1

您无法立即安全地终止线程。相反,您的任务应遵守中断并在中断时停止。如果使用 ,则所有正在运行的任务都将中断。ThreadPoolExecutor.shutdownNow()

唯一的替代方案是将线程放在单独的进程中,发出信号来终止进程。


答案 2

老问题,但我认为你可以扩展ThreadPoolExecutor来捕获Execute()中正在运行的线程引用。当 shutdownNow() 被调用时,你可以停止() 所有正在运行的线程。虽然我强烈建议在你的任务中依赖isInterrupted()。

示例代码 ->

public class KillableThreadPoolExecutor extends ThreadPoolExecutor {

    private final Map<Runnable, Thread> executingThreads;

    public KillableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, String threadNamePrefix) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, new YoungMemorySafeLinkedBlockingQueue<Runnable>(), ThreadFactories.create(threadNamePrefix));
        executingThreads = new HashMap<>(maximumPoolSize);
    }

    @Override
    protected synchronized void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        executingThreads.put(r, t);
    }

    @Override
    protected synchronized void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        if(executingThreads.containsKey(r)) {
            executingThreads.remove(r);
        }
    }

    @Override
    public synchronized List<Runnable> shutdownNow() {
        List<Runnable> runnables = super.shutdownNow();
        for(Thread t : executingThreads.values()) {
            t.stop();
        }
        return runnables;
    }
}