问题
I am using an ExecutorService
to implement a 3-thread pool, and CountDownLatch to monitor the completion of all threads, for further processing.
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?
回答1:
Use the overloaded variant of await that accepts a timeout.
countDownLatch.await(45, TimeUnit.SECONDS);
来源:https://stackoverflow.com/questions/15245629/abort-countdownlatch-await-after-time-out