forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIvokeAnyEx.java
More file actions
40 lines (27 loc) · 1010 Bytes
/
IvokeAnyEx.java
File metadata and controls
40 lines (27 loc) · 1010 Bytes
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
package com.zetcode;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class IvokeAnyEx {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newFixedThreadPool(5);
Callable<String> task1 = () -> {
Thread.sleep(3000);
return "task 1 result";
};
Callable<String> task2 = () -> {
Thread.sleep(1500);
return "task 2 result";
};
Callable<String> task3 = () -> {
Thread.sleep(4000);
return "task3 result";
};
// invokeAny returns the result of the fastest callable
var result = executorService.invokeAny(Arrays.asList(task1, task2, task3));
System.out.println(result);
executorService.shutdown();
}
}