等待 Future 列表的提前终止
在处理由 future 表示的异步任务时,等待所有处理完成通常至关重要。完成或发生错误。然而,即使在发生错误后,不必要地等待所有任务完成也是不可取的。
要解决此问题,请考虑以下步骤:
利用a CompletionService:
按顺序监视 Future:
取消剩余任务:
这里是一个示例演示了这种方法:
<code class="java">Executor executor = Executors.newFixedThreadPool(4); CompletionService<SomeResult> completionService = new ExecutorCompletionService<SomeResult>(executor); // 4 tasks for(int i = 0; i < 4; i++) { completionService.submit(new Callable<SomeResult>() { public SomeResult call() { // Processing code return result; } }); } int received = 0; boolean errors = false; while(received < 4 && !errors) { Future<SomeResult> resultFuture = completionService.take(); // Blocks until available try { SomeResult result = resultFuture.get(); received ++; // Process the result } catch(Exception e) { // Log or handle the error errors = true; } if (errors) { // Cancel any remaining tasks executor.shutdown(); break; } }</code>
以上是使用 Future 时如何有效处理错误和提前终止?的详细内容。更多信息请关注PHP中文网其他相关文章!