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

dea*_*ock 12 java multithreading threadpool threadpoolexecutor

我在里面有很多任务TheadPoolExecutor.我的界面上有一个停止按钮,可以ThreadPoolExecutor立即终止所有线程.我正在寻找一种方法来做到这一点.(没有shutDown()shutDownNow()).

谢谢

Pet*_*rey 14

你无法立即安全地杀死线程.您的任务应该尊重中断并在中断时停止.如果使用ThreadPoolExecutor.shutdownNow(),则所有正在运行的任务都将被中断.

唯一的选择是在一个单独的进程中的线程发出一个信号来杀死进程.


Dan*_* C. 6

shutdown()只会使ThreadPoolExecutor拒绝所有新submited任务,并从队列中删除(如果ThreadPool是无界队列执行人)的尚未完成的任务.该shutdownNow()会做同样的,也将调用该interrupt()方法Thread.因此,在您的run()方法中,您应该正确处理它:

try {
   Thread.sleep(1000);
} catch (InterruptedException ie) {
   // Handle the exception, and close resources.
}
Run Code Online (Sandbox Code Playgroud)


小智 5

老问题了,但我认为您可以扩展ThreadPoolExecutor来捕获beforeExecute()中正在运行的线程引用。当shutdownNow()被调用时,您可以stop()所有正在运行的线程。尽管我强烈建议您在任务中依赖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;
    }
}
Run Code Online (Sandbox Code Playgroud)