我需要一次执行4个任务,如下所示:
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
taskExecutor.execute(new MyTask());
}
//...wait for completion somehow
Run Code Online (Sandbox Code Playgroud)
一旦完成所有内容,我该如何收到通知?现在我想不出比设置一些全局任务计数器更好的事情,并在每个任务结束时减少它,然后在无限循环中监视这个计数器变为0; 或获得一个Futures列表,并在无限循环监视器isDone中为所有这些.什么是更好的解决方案不涉及无限循环?
谢谢.
java parallel-processing concurrency multithreading executorservice
这是我的简单代码:
public class Main4 {
public static void main(String[] args) {
System.out.println("Hello from thread: "+Thread.currentThread().getName());
new Game().run();
System.out.println("I am dying ... ");
}
static class Game {
public void run() {
value();
}
private int value() {
int number = 0;
CompletionStage<Void> c = calculate().thenApply(i -> i + 3).thenAccept(i -> System.out.println("I am done, and my value is " + i));
return number;
}
private CompletionStage<Integer> calculate() {
CompletionStage<Integer> completionStage = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
System.out.println("I am in the thread: …Run Code Online (Sandbox Code Playgroud) java multithreading threadpool completable-future completion-stage