-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathRunTasksCompletableFuture.java
More file actions
58 lines (41 loc) · 1.47 KB
/
RunTasksCompletableFuture.java
File metadata and controls
58 lines (41 loc) · 1.47 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
package com.zetcode;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
class Task {
private final int duration;
public Task(int duration) {
this.duration = duration;
}
public int doTask() {
System.out.printf("%s %n", Thread.currentThread().getName());
try {
Thread.sleep(duration * 1000);
} catch (final InterruptedException e) {
throw new RuntimeException(e);
}
return duration;
}
}
public class RunTasksCompletableFuture {
public static void main(String[] args) {
long start = System.nanoTime();
List<Task> tasks = IntStream.range(0, 10)
.mapToObj(i -> new Task(1))
.collect(toList());
List<CompletableFuture<Integer>> futures =
tasks.stream()
.map(task -> CompletableFuture.supplyAsync(task::doTask))
.collect(Collectors.toList());
List<Integer> result =
futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList());
long end = System.nanoTime();
long duration = (end - start) / 1_000_000;
System.out.printf("Run %d tasks in %d millis\n", tasks.size(), duration);
System.out.println(result);
}
}