forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCallableEx.java
More file actions
63 lines (43 loc) · 1.66 KB
/
CallableEx.java
File metadata and controls
63 lines (43 loc) · 1.66 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
package com.zetcode;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
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;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public class CallableEx {
private static class RandomTask implements Callable<Integer> {
@Override
public Integer call() {
int value = new Random().nextInt(1000);
try {
System.out.printf("task %s started computing...%n", Thread.currentThread().getName());
MILLISECONDS.sleep(value);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("task %s is returning value: %d%n", Thread.currentThread().getName(), value);
return value;
}
}
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
System.out.println("submitting tasks for execution");
List<Future<Integer>> results = new LinkedList<>();
for (int i = 0; i < 6; i++) {
results.add(executor.submit(new RandomTask()));
}
System.out.println("getting results from futures");
for (Future<Integer> result : results) {
try {
System.out.printf("computed result: %d%n", result.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
executor.shutdown();
}
}