-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
69 lines (49 loc) · 1.78 KB
/
Main.java
File metadata and controls
69 lines (49 loc) · 1.78 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//printNames();
Future<Integer> future = calculate(10);
while(!future.isDone()) {
System.out.println("Calculating...");
Thread.sleep(300);
}
Integer result = future.get();
System.out.println(result);
System.out.println("===============================");
List<Integer> rawInts = new ArrayList<>(3);
rawInts.add(2);
rawInts.add(10);
rawInts.add(100);
List<Future<Integer>> futures = calculateList(rawInts);
for(Future<Integer> value: futures){
Integer individualResult = value.get();
System.out.println(individualResult);
}
}
public static ExecutorService executor = Executors.newFixedThreadPool(4);
public static Future<Integer> calculate(Integer input) {
Callable<Integer> n = () -> {
Thread.sleep(1000);
return input * input;
};
// return executor.submit(() -> {
// Thread.sleep(1000);
// return input * input;
// });
return executor.submit(n);
}
public static List<Future<Integer>> calculateList(List<Integer> rawInts) throws InterruptedException {
List<Callable<Integer>> todo = new ArrayList<Callable<Integer>>(3);
for(Integer value: rawInts){
Callable<Integer> n = () -> {
Thread.sleep(1000);
System.out.println("calculating value: "+value);
return value * value;
};
todo.add(n);
}
return executor.invokeAll(todo);
}
}