Java 超时后中止countDownLatch.Wait()
我正在使用一个Java 超时后中止countDownLatch.Wait(),java,multithreading,executorservice,executors,Java,Multithreading,Executorservice,Executors,我正在使用一个ExecutorService来实现一个3线程池,并使用CountDownLatch来监控所有线程的完成情况,以便进一步处理 ExecutorService threadExecutor = Executors.newFixedThreadPool(3); CountDownLatch countDownLatch = new CountDownLatch(3); AuthorisationHistoryTask task1 = new AuthorisationHist
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);
}
ExecutorService threadExecutor=Executors.newFixedThreadPool(3);
CountDownLatch CountDownLatch=新的CountDownLatch(3);
授权历史任务任务1=
新授权历史任务(commonDataThread,countDownLatch);
预授权历史任务任务2=
新的预授权历史任务(userID、sessionID、commonDataThread、countDownLatch);
SettlementThistTask4=新的SettlementThistTask(commonDataThread,countDownLatch);
Future futureAuthHistory=threadExecutor.submit(任务1);
Future futurePreAuthHist=threadExecutor.submit(任务2);
Future futureSettleHist=threadExecutor.submit(任务4);
threadExecutor.shutdown();
试一试{
倒计时闩锁。等待();
}捕获(中断异常e){
logCommon(“InterruptedException”,类名称);
}catch(ExecutionException ex){
logCommon(“InterruptedException”,类名称);
}
我使用了
countDownLatch.await()
等待所有线程完成。我希望此进程countDownLatch.await()
在超时情况下中止,例如45秒。如何实现这一点?使用接受超时的重载变量
countDownLatch.await(45, TimeUnit.SECONDS);
这是行不通的。即使进程在2-3秒内完成,也会将线程保持45秒。不,不会,它会等待指定的时间。只要锁存器在任务中被倒计时到零,它就保证等待完成时间或超时中的*较小者。@DavidDoria-确实应该如此。谢谢你发现了,而且。。。已修复。@Perception:如果未达到计数,但wait()函数超时,您知道闩锁是否仍然可用吗?换句话说,我是否可以超时,检查某些内容,然后再次调用wait()方法,并且仍然让另一个线程中的“count()”发出信号?只有countDownLatch之前的代码是异步的,此代码才有帮助。如果你把同步代码-它不会帮助你。