4

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

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

4

1 回答 1

6

请参阅有关 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

    }
};
于 2013-08-13T09:06:54.667 回答