java - 如何让主线程等待执行器服务线程完成
问题描述
这是我的主线程,在每个进程中我都在调用执行器服务线程。在第 4 行,在更新状态之前,我想等待我的所有线程完成
line 1- missingStrategyContext.process(FileType.CARD, programId, fromDate, toDate, channel);
line 2- missingStrategyContext.process(FileType.TRANSACTION, programId, fromDate, toDate, channel);
line 3- missingStrategyContext.process(FileType.REFUND, programId, fromDate, toDate, channel);
line 4- processingLog.setProcessingStatus(TransactionState.SUCCESS.name());
在每个进程中,我决定文件类型值我必须调用哪种策略
public void process(FileType fileType, String programId, Long fromDate, Long toDate, String channel){
map.get(fileType).process(programId, fromDate, toDate, channel, fileType);
}
然后根据文件类型,我实现了我的处理方法并在每个文件类型实现中调用了执行器服务
@Override
public void process(String programId, Long fromDate, Long toDate, String channel, FileType fileType) {
MultiTenantTxMgmt multiTenantTxMgmt = MultiTenantTxMgmtUtil.get(programId);
EntityManager entityManager = null;
List<MissingReason> reasonList = new ArrayList<>();
try {
entityManager = multiTenantTxMgmt.getEntityManager();
reasonList = missingDataRepository.getDistinctMissingReasonForFileType(entityManager, fileType, TransactionState.READYTOATTEMPT);
}catch (Exception exception) {
logger.error(exception.getMessage(), exception);
throw new UnkownBatchSaveException();
} finally {
entityManager.close();
}
reasonList.forEach(
missingReason -> deExecutorService.dotask(() ->
missingTransactionStrategyContext.processMissingV3(missingReason, programId, fromDate, toDate, channel, fileType)
)
);
}
解决方案
您可以使用CountDownLatch#await
. 例如从文档复制:
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(N);
for (int i = 0; i < N; ++i) // create and start threads
new Thread(new Worker(startSignal, doneSignal)).start();
doSomethingElse(); // don't let run yet
startSignal.countDown(); // let all threads proceed
doSomethingElse();
doneSignal.await(); // wait for all to finish
推荐阅读
- mysql - 将日期转换为字符串,然后在 mysql 中再次转换为日期。在 mysql 中组合 2 个函数
- python - 有效的成对和
- python - 将大字符串转换为数据框
- python - Unable to apply Django migration in Postgres DB
- flutter - 输入“行为主题”
' 不是类型 'Stream 的子类型 '的'流' - rust - 如何在 Substrate 中从 Polkadot.js 实现 blake2AsHex 功能?
- snakemake - Snakemake 可变文件数
- c# - 获取用户的组策略设置
- glibc - 是否可以从 C 代码运行 __libc_start_main ?
- java - 如何从 LinkedHashMap 中检索最后 N 个元素