如何阻止Callable提交给ExecutorService?
我正在尝试实现一个示例应用程序来测试Callable
和ExecutorService
接口。
在我的应用程序中,我声明:
ExecutorService exSvc = Executors.newSingleThreadExecutor();
然后:
Future test = exSvc.submit( new Callable() { public Integer call() { for(int i = 0; i < 1000; i++){ System.out.println(i); } return 1; } });
现在我试图在终止之前停止进程,我正在使用exSvc.shutdownNow()
但它不起作用。
为了优雅地停止经典Thread
我通常使用某种条件变量 。 遵循ExecutorService
的常用方法是什么?
Future.cancel(true)
和ExecutorService.shutdownNow()
使用线程中断。 只要您不在任务中进行不间断的阻塞调用,您只需要正确处理中断条件,如下所示:
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); }
如果您进行不间断的阻塞调用(例如网络IO),事情会变得更加复杂,您需要以某种方式手动中断它们,例如,通过关闭底层套接字。
这就是我用FixedThreadPool
做的FixedThreadPool
,希望它有一些帮助。
ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); List> results = new ArrayList<>(); for (int i = 0; i < numberOfJobs; i++) { MyCallableJob job = new MyCallableJob (...); results.add(pool.submit(job)); } for (Future result : results) { try { result.get(); } catch (InterruptedException | ExecutionException ignorable) { } } pool.shutdown();