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

android– 在threadpoolexecutor中停止运行任务的最佳方法是什么?,第1张

概述我正在Android中实现JavaThreadPoolExecutor.我需要停止并从池中删除正在运行的任务.我已经使用submit(Runnable)和Future.cancel()方法实现了这一点.提交任务的代码如下:publicFuture<?>submitTask(RunnablerunnableTask)throwsCustomException{if(runnableTask=

我正在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.");    }}

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

解决方法:

有关Future任务,请参阅documentation.据我所知,如果执行开始,我们无法取消它.然后我们可以做的是取消取消的效果是中断正在运行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中停止运行任务的最佳方法是什么?全部内容,希望文章能够帮你解决android – 在threadpoolexecutor中停止运行任务的最佳方法是什么?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1106893.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存