在超时后终止countDownLatch.await()方法的执行。

12

我正在使用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() 来等待所有线程完成。如果超时,比如说45秒,我希望能够中止这个进程 countDownLatch.await() 。我该如何实现?
1个回答

32
使用接受超时参数的await重载变体。
countDownLatch.await(45, TimeUnit.SECONDS);

这个不起作用。即使进程已经在2-3秒内完成,它仍会保持线程45秒。 - user2122524
12
不,它并不会立即等待,而是等待至多指定的时间。只要在任务中计数器被倒数至零,它就保证会等待完成时间和超时时间中较短的那个。 - Perception
@DavidDoria - 的确应该这样。感谢你发现了这个问题,已经修复。 - Perception
@Perception:你知道如果计数没有达到但await()函数超时了,锁还能正常工作吗?换句话说,我可以超时后检查一些东西,再次调用await()方法,并在另一个线程中通过'count()'发出信号吗? - Brian Reinhold
这段代码只有在 countDownLatch 之前的代码是异步的情况下才有用。如果你放置同步代码,它将无法帮助你。 - Kostadin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接