java 超时后中止 countDownLatch.await()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15245629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:57:59  来源:igfitidea点击:

Abort countDownLatch.await() after time out

javamultithreadingexecutorserviceexecutors

提问by user2122524

I am using an ExecutorServiceto implement a 3-thread pool, and CountDownLatch to monitor the completion of all threads, for further processing.

我使用 anExecutorService来实现一个 3 线程池,并使用 CountDownLatch 来监视所有线程的完成情况,以便进一步处理。

ExecutorService threadExecutor = Executors.newFixedThreadPool(3);
CountDownLatch countDownLatch = new CountDownLatch(3);

AuthorisationHistoryTask task1 =
    new AuthorisationHistoryTask(commonDataThread, countDownLatch );
PreAuthHistoryTask task2 = 
    new PreAuthHistoryTask(userID,sessionID, commonDataThread, countDownLatch );

SettlementHistTask task4 = new SettlementHistTask(commonDataThread,countDownLatch);

Future<Map<String, Object>> futureAuthHistory = threadExecutor.submit (task1);
Future<Map<String, Object>> futurePreAuthHist = threadExecutor.submit (task2);
Future<Map<String, Object>> futureSettleHist = threadExecutor.submit(task4);

threadExecutor.shutdown();

try {
     countDownLatch.await();
}catch (InterruptedException e) { 
     logger.logCommon("InterruptedException",CLASS_NAME);                     
}catch (ExecutionException ex) { 
     logger.logCommon("InterruptedException",CLASS_NAME); 
}

I have used countDownLatch.await()to wait till all the threads are completed. I want this process countDownLatch.await()to abort in case of TIME OUT say 45 secs. How can I implement this?

我习惯countDownLatch.await()等到所有线程都完成。我希望这个过程countDownLatch.await()在 TIME OUT 的情况下中止,比如 45 秒。我该如何实施?

回答by Perception

Use the overloaded variant of awaitthat accepts a timeout.

使用await接受超时的重载变体。

countDownLatch.await(45, TimeUnit.SECONDS);