-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCallableDemo.java
More file actions
80 lines (70 loc) · 2.05 KB
/
CallableDemo.java
File metadata and controls
80 lines (70 loc) · 2.05 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
70
71
72
73
74
75
76
77
78
79
80
/**
* <html>
* <body>
* <P> Copyright 1994 JsonInternational</p>
* <p> All rights reserved. - https://github.com/Jasonandy/Java-Core-Advanced </p>
* <p> Created by Jason</p>
* </body>
* </html>
*/
package cn.ucaner.core.concurrent;
import java.util.ArrayList;
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;
/**
* @Package:cn.ucaner.core.concurrent
* @ClassName:CallableDemo
* @Description: <p> CallableDemo </p>
* @Author: -
* @CreatTime:2018年6月12日 下午3:50:49
* @Modify By:
* @ModifyTime: 2018年6月12日
* @Modify marker:
* @version V1.0
*/
public class CallableDemo {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<>();
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);
e.printStackTrace();
} catch (ExecutionException e) {
System.out.println(e);
e.printStackTrace();
} finally {
exec.shutdown();
}
}
}
}
class TaskWithResult implements Callable<String> {
private int id;
public TaskWithResult(int id) {
this.id = id;
}
@Override
public String call() throws Exception {
return "result of TaskWithResult " + id;
}
}
//Outputs
//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