超时后中止countDownLatch.await()(Abort countDownLatch.a

2019-07-21 02:26发布

我使用的是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()在时间的情况下中止OUT说45秒。 我怎样才能实现呢?

Answer 1:

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

countDownLatch.await(45, TimeUnit.SECONDS);


文章来源: Abort countDownLatch.await() after time out