1 import java.util.concurrent.Callable;
2 import java.util.concurrent.ExecutionException;
3 import java.util.concurrent.ExecutorService;
4 import java.util.concurrent.Executors;
5 import java.util.concurrent.Future;
6
7 public class CallableAndFuture1 {
8
9 public static void main(String[] args) {
10 ExecutorService service = Executors.newSingleThreadExecutor();
11
12 Future<Integer> future = service.submit( new Callable<Integer>() {
13
14 @Override
15 public Integer call() throws Exception {
16 System. out.println("子线程" + Thread.currentThread().getName() + "在进行计算");
17 Thread. sleep(3000);
18
19 int sum = 0;
20 for (int i = 0; i < 100; i++) {
21 sum += i;
22 }
23 return sum;
24 }
25 });
26
27 System. out.println("主线程" + Thread.currentThread ().getName() + "在执行任务" );
28
29 try {
30 System. out.println("子线程运行结果" + future.get());
31 } catch (InterruptedException e) {
32 e.printStackTrace();
33 } catch (ExecutionException e) {
34 e.printStackTrace();
35 }
36
37 System. out.println("所有任务执行完毕" );
38
39 }
40 }
Callable、Future和FutureTask使用说明
原文:http://www.cnblogs.com/zhangyuhang3/p/6872677.html