我正在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.");
}
}
问题:这些任务实际上并未取消。请让我知道我错在哪里。任何帮助将不胜感激。
答案 0 :(得分:5)
请参阅有关未来任务的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
}
};