1. Main
public class Main {
public static void main(String[] args) throws Exception {
FutureContext futureContext = new FutureContext();
ExecutorService executorService = Executors.newCachedThreadPool();
for(int i = 0; i <= 9; i++) {
Future<Integer> future = executorService.submit(new Worker(i * 10 + 1, i * 10 + 10));
futureContext.addFuture(future);
}
executorService.shutdown();
new Thread(new Consumer(futureContext)).start();
System.out.println("Main thread finished.");
}
}
2. Worker
public class Worker implements Callable<Integer> {
private int start;
private int end;
public Worker(int start, int end) {
this.start = start;
this.end = end;
}
public Integer call() throws Exception {
int sum = 0;
for (int i = start; i <= end; i++) {
sum += i;
}
System.out.println("Work[" + start + " , " + end + "], finished.");
return sum;
}
}
3. FutureContext
public class FutureContext {
private List<Future<Integer>> futureList = new ArrayList<Future<Integer>>();
public List<Future<Integer>> getFutureList() {
return futureList;
}
public void addFuture(Future<Integer> future) {
this.futureList.add(future);
}
}
4. Consumer
public class Consumer implements Runnable {
private FutureContext futureContext;
public Consumer(FutureContext futureContext) {
this.futureContext = futureContext;
}
public void run() {
try{
Thread.sleep(3000);
int sum = 0;
for(Future<Integer> fu : futureContext.getFutureList()) {
sum += fu.get();
}
System.out.println("Three seconds later, Consumer finished, sum=" + sum);
}catch(Exception e) {
e.printStackTrace();
}
}
}
Console