超时后中止countDownLatch.await()

时间:2013-03-06 11:04:27

标签: java multithreading executorservice executors

我使用ExecutorService实现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); 
}

我使用countDownLatch.await()等待所有线程完成。我希望这个过程countDownLatch.await()在TIME OUT表示45秒后中止。我该如何实现呢?

1 个答案:

答案 0 :(得分:21)

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

countDownLatch.await(45, TimeUnit.SECONDS);