[英]How to stop a Callable submitted to ExecutorService?
I'm trying to implement a sample application to test Callable
and ExecutorService
interfaces. 我正在尝试实现一个示例应用程序来测试
Callable
和ExecutorService
接口。
In my app I have declared: 在我的应用程序中,我声明:
ExecutorService exSvc = Executors.newSingleThreadExecutor();
Then: 然后:
Future<Integer> test = exSvc.submit(
new Callable<Integer>() {
public Integer call() {
for(int i = 0; i < 1000; i++){
System.out.println(i);
}
return 1;
}
});
Now I'm trying to stop the process before it terminate, I'm using exSvc.shutdownNow()
but it doesn't work. 现在我试图在终止之前停止进程,我正在使用
exSvc.shutdownNow()
但它不起作用。
To stop gracefully a classical Thread
I usually use some kind of condition variable . 为了优雅地停止经典
Thread
我通常使用某种条件变量 。 Which is a common approach to follow with ExecutorService
? 遵循
ExecutorService
的常用方法是什么?
Future.cancel(true)
and ExecutorService.shutdownNow()
use thread interruption. Future.cancel(true)
和ExecutorService.shutdownNow()
使用线程中断。 As long as you don't make uninterruptable blocking calls in your task, all you need is to handle interrupted condition correctly, something like this: 只要您不在任务中进行不间断的阻塞调用,您只需要正确处理中断条件,如下所示:
for(int i = 0; i < 1000; i++){
// Uses isInterrupted() to keep interrupted status set
if (Thread.currentThread().isInterrupted()) {
// Cannot use InterruptedException since it's checked
throw new RuntimeException();
}
System.out.println(i);
}
If you make uninterruptable blocking calls (such as network IO), things become more complex, you need to interrupt them manually somehow, for example, by closing the underlying sockets. 如果你进行不间断的阻塞调用(例如网络IO),事情变得更加复杂,你需要以某种方式手动中断它们,例如,通过关闭底层套接字。
This is how I'd do it with a FixedThreadPool
, hope it's of some help. 这就是我使用
FixedThreadPool
,希望它有所帮助。
ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
List<Future<Void>> results = new ArrayList<>();
for (int i = 0; i < numberOfJobs; i++) {
MyCallableJob job = new MyCallableJob (...);
results.add(pool.submit(job));
}
for (Future<Void> result : results) {
try { result.get(); }
catch (InterruptedException | ExecutionException ignorable) { }
}
pool.shutdown();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.