android - 在 threadpoolexecutor 中停止运行任务的最佳方法是什么?

标签 android threadpoolexecutor

我正在 Android 中实现 Java ThreadPoolExecutor。我需要停止并从我的池中删除正在运行的任务。

我已经通过使用 submit(Runnable) 和 Future.cancel() 方法实现了这一点。

提交任务的代码如下:

public Future<?> submitTask(Runnable runnableTask) throws CustomException {
    if (runnableTask == null) {
        throw new CustomException("Null RunnableTask.");
    }
    Future<?> future = threadPoolExecutor.submit(runnableTask);
    return future;
}

submit() 返回的 Future 被传递给下面的方法。 取消任务的代码如下:

public void cancelRunningTask(Future<?> future) throws CustomException {
    if (future == null) {
        throw new CustomException("Null Future<?>.");
    }
    if (!(future.isDone() || future.isCancelled())) {
        if (future.cancel(true))
            MyLogger.d(this, "Running task cancelled.");
        else
            MyLogger.d(this, "Running task cannot be cancelled.");
    }
}

问题: 任务实际上并没有被取消。请让我知道我哪里错了。任何帮助将不胜感激。

最佳答案

请参阅documentation关于 future 的任务。据我所知,如果执行开始了,我们就不能取消它。那么为了达到取消的效果,我们可以做的就是中断正在运行Future任务的线程

mayInterruptIfRunning - true

在你的 runnable 中,在不同的地方,你需要检查线程是否被中断,如果中断则返回,只有这样我们才能取消它。

Thread.isInterrupted()

示例:

private Runnable ExecutorRunnable = new Runnable() {

    @Override
    public void run() {

        // Before coming to this run method only, the cancel method has
        // direct grip. like if cancelled, it will avoid calling the run
        // method.

        // Do some Operation...

        // Checking for thread interruption
        if (Thread.currentThread().isInterrupted()) {
            // Means you have called Cancel with true. So either raise an
            // exception or simple return.
        }

        // Do some Operation...

        // Again Checking for thread interruption
        if (Thread.currentThread().isInterrupted()) {
            // Means you have called Cancel with true. So either raise an
            // exception or simple return.
        }

        // Similarly you need to check for interruption status at various
        // points

    }
};

关于android - 在 threadpoolexecutor 中停止运行任务的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18204454/

相关文章:

android - 在图像编辑器中处理大位图

android - 完成 Activity 后如何通过对话框运行 AsyncTask?

java - 替换 fragment 时如何防止 "java.lang.IllegalStateException: Fragment already added"?

java - 如果在 java 中声明 ExecutorService 后错过 shutdown 子句会发生什么

java - 修复线程池: pause until thread available?

java - ThreadPoolExecutor - 在队列之前使用线程

java - while 循环导致 Activity 屏幕什么都不显示?

java - 从 Android Websocket 客户端发送消息

java - 如何访问 ThreadPoolExecutor 中正在运行的线程?

java - 不使用全局变量读取线程的当前状态