【发布时间】:2020-09-03 05:31:26
【问题描述】:
我正在尝试使用ExecutorService 在多个线程中处理相对较大的Stream 或List。该方法看起来像这样。
public void initMigration() {
ExecutorService executorService = Executors.newCachedThreadPool();
try (Stream<List<Record4<Integer, Integer, String, byte[]>>> streamOfLists = getStreamOfLists()) {
streamOfLists.forEach(record4List -> {
Runnable runnable = () -> {
try {
final List<Attachment> attachments = RecordProcessor.prepareAttachmentsToPost(record4List);
LOGGER.info("Invoking POST with payload {}", attachments);
Collection<UploadLink> uploadLinks = restClient.postAttachments(attachments);
restClient.processUploadLinksAndUpload(RecordProcessor.recordsIntoPojo(record4List), uploadLinks);
} catch (ExceptionA | ExceptionB e) {
e.printStackTrace();
}
};
executorService.submit(runnable);
});
}
LOGGER.info("Shutting down the ExecutorService");
executorService.shutdown();
}
基本上,我在这里要做的是,对于Stream 中的每个List,正在创建一个Runnable 并将其提交给ExecutorService。它似乎工作正常。但是,我现在真正想做的是看看是否有任何方法可以让ExecutorService 运行从Stream 中的第一个List 获得的第一个Runnable,同时阻止其他Runnables 直到
它的执行,然后继续运行其他Runnables(并行)。真的可以在这方面使用一些帮助。
【问题讨论】:
标签: java executorservice java-threads