-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCallableDemo.java
More file actions
49 lines (40 loc) · 1.35 KB
/
CallableDemo.java
File metadata and controls
49 lines (40 loc) · 1.35 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
package com.loon.multithreading;
import java.util.ArrayList;
import java.util.concurrent.*;
/**
* Created with IntelliJ IDEA.
* User: Loon
* Date: 13-4-8
* Time: 下午10:47
* To change this template use File | Settings | File Templates.
*/
public class CallableDemo {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<Future<String>>();
for (int i = 0; i < 5; i++) {
results.add(executorService.submit(new TaskWithResult(i)));
}
for (Future<String> str : results) {
try {
System.out.println(str.get());
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (ExecutionException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
executorService.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;
}
}