I found this code in a project:
int threadCount = 10;
CompletableFuture<?>[] futures = new CompletableFuture<?>[threadCount];
for (int i = 0; i < threadCount; i++) {
futures[i] = CompletableFuture.runAsync(() -> { process.run(queue); });
}
// Wait all futures
CompletableFuture.allOf(futures).join();
What's the difference with doing this?
ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
CompletableFuture.runAsync(() -> { process.run(queue); }, threadPool );
Thanks for your explanation.
int threadCount = 10;
CompletableFuture<?>[] futures = new CompletableFuture<?>[threadCount];
for (int i = 0; i < threadCount; i++) {
futures[i] = CompletableFuture.runAsync(() -> { process.run(queue); });
}
// Wait all futures
CompletableFuture.allOf(futures).join();
In this case, you creates set of completable futures which are result of executing asynchronous code in common ForkJoin pool. Then process waits until all futures are completed.
ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
CompletableFuture.runAsync(() -> { process.run(queue); }, threadPool );
In this case, you are executing code in specified thread pool.
The differences between these code blocks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.