-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCallableDemo.java
More file actions
65 lines (53 loc) · 1.53 KB
/
CallableDemo.java
File metadata and controls
65 lines (53 loc) · 1.53 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
package concurrency;
import java.io.*;
import java.util.concurrent.*;
import java.util.*;
/**
* RUN:
* javac concurrency/CallableDemo.java && java concurrency.CallableDemo
*
* OUTPUT:
* result of TaskWithResult 0
* result of TaskWithResult 1
* result of TaskWithResult 2
* result of TaskWithResult 3
* result of TaskWithResult 4
* result of TaskWithResult 5
* result of TaskWithResult 6
* result of TaskWithResult 7
* result of TaskWithResult 8
* result of TaskWithResult 9
*/
public class CallableDemo {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<Future<String>>();
for (int i = 0; i < 10; i++) {
results.add(exec.submit(new TaskWithResult(i)));
}
for (Future<String> fs : results) {
try {
System.out.println(fs.get());
}
catch (InterruptedException e) {
System.out.println(e);
return;
}
catch (ExecutionException e) {
System.out.println(e);
}
finally {
exec.shutdown();
}
}
}
}
class TaskWithResult implements Callable<String> {
private int id;
public TaskWithResult(int id) {
this.id = id;
}
public String call() {
return "result of TaskWithResult " + id;
}
}