forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvokeAllEx.java
More file actions
46 lines (31 loc) · 1.15 KB
/
InvokeAllEx.java
File metadata and controls
46 lines (31 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.zetcode;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class InvokeAllEx {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newFixedThreadPool(5);
Callable<String> task1 = () -> {
Thread.sleep(2000);
return "task 1 result";
};
Callable<String> task2 = () -> {
Thread.sleep(1000);
return "task 2 result";
};
Callable<String> task3 = () -> {
Thread.sleep(4000);
return "task 3 result";
};
List<Callable<String>> tasks = List.of(task1, task2, task3);
List<Future<String>> futures = executorService.invokeAll(tasks);
for (Future<String> future : futures) {
// results are printed after all the futures are completed
System.out.println(future.get());
}
executorService.shutdown();
}
}