1 public class FutureDemo1 {
2
3 public static void main(String[] args) throws InterruptedException, ExecutionException {
4 FutureTask future = new FutureTask(new Callable() {
5 @Override
6 public String call() throws Exception {
7 return new RealData().costTime();
8 }
9 });
10 ExecutorService service = Executors.newCachedThreadPool();
11 service.submit(future);
12
13 System.out.println(“RealData方法调用完毕”);
14 // 模拟主函数中其他耗时操作
15 doOtherThing();
16 // 获取RealData方法的结果
17 System.out.println(future.get());
18 }
19
20 private static void doOtherThing() throws InterruptedException {
21 Thread.sleep(2000L);
22 }
23 }
24
25 class RealData {
26
27 public String costTime() {
28 try {
29 // 模拟RealData耗时操作
30 Thread.sleep(1000L);
31 return “result”;
32 } catch (InterruptedException e) {
33 e.printStackTrace();
34 }
35 return “exception”;
36 }
37
38 }
通过Future实现
与上述FutureTask不同的是, RealData需要实现Callable接口
1 public class FutureDemo2 {
2
3 public static void main(String[] args) throws InterruptedException, ExecutionException {
4 ExecutorService service = Executors.newCachedThreadPool();
5 Future future = service.submit(new RealData2());
6
7 System.out.println(“RealData2方法调用完毕”);
8 // 模拟主函数中其他耗时操作
9 doOtherThing();
10 // 获取RealData