[英]Cancelling a Task in threadPoolExecutor
I instantiated threadPoolExecutor and submitted asynchronous task to pool and got Future object and then i tried to cancel the task, cancel operation is not working...我实例化了 threadPoolExecutor 并将异步任务提交到池并获得了 Future 对象,然后我尝试取消任务,取消操作不起作用......
The task is related to database calls.该任务与数据库调用有关。
Code is as below,代码如下,
private ThreadPoolExecutor _scheduledThreadPool;
_scheduledThreadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(_poolSize, factory);
Future<Object> task = _scheduledThreadPool.submit(task);
tasks.cancel(true);
After the above code, I observed the _scheduledThreadPool.getQueue() is giving empty.在上面的代码之后,我观察到 _scheduledThreadPool.getQueue() 是空的。
I am working on this from few days but not worked.我从几天开始就在做这个,但没有工作。
Please help me how to cancel a task individually in ThreadPoolExecutor.请帮助我如何在 ThreadPoolExecutor 中单独取消任务。
thanks谢谢
If the task is already running at the time that cancel() is called-- which is what appears to be happening in your case-- then this won't "magically" guarantee that the task will stop running in the way that you expect.如果在调用 cancel() 时任务已经在运行 - 这就是您的情况似乎正在发生的事情 - 那么这不会“神奇地”保证任务将停止以您期望的方式运行. The thread running the task will be interrupted , and the code performed by your task has to handle this with your desired behaviour.
运行任务的线程将被中断,您的任务执行的代码必须以您想要的行为来处理这个问题。
你可以试试:
_scheduledThreadPool.getQueue().clear();
We have a Future
object here:我们在这里有一个
Future
对象:
Future<Object> task = _scheduledThreadPool.submit(task);
ThreadPoolExecutor
uses FutureTask
as the default Future
implementation. ThreadPoolExecutor
使用FutureTask
作为默认的Future
实现。 And FutureTask
uses thread interruption to cancel the task .而
FutureTask
使用线程中断来取消任务。 So it invokes Thread.intterrupt
on the worker thread.所以它在工作线程上调用
Thread.intterrupt
。
However, for the cancellation to happen, the task must be responsive to interruptions.但是,要取消,任务必须对中断做出响应。 In other words, it must check whether the current thread is interrupted by invoking
Thread.interrupted
/ Thread.currentThread().isInterrupted
.换句话说,它必须通过调用
Thread.interrupted
/ Thread.currentThread().isInterrupted
来检查当前线程是否被中断。 As an example, we're checking the interruption status in a loop:例如,我们在循环中检查中断状态:
final Runnable task = () -> {
while (!Thread.currentThread().isInterrupted()) {
// Do work.
}
}
Alternatively, the task must be blocked on code that respects interruption, like LinkedBlockingQueue.take
.或者,必须在尊重中断的代码上阻止任务,例如
LinkedBlockingQueue.take
。 The standard libraries generally throw an InterruptedException
when they detect an interruption.标准库在检测到
InterruptedException
时通常会抛出InterruptedException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.