Future接口代表异步计算的结果,并且提供方法来检测异步过程的进展。Callable接口与Runnable接口比较类似,提供线程的执行体,即run方法的内容。
Future与Callable结合使用开启一个新线程执行,最大的特点是能提供返回值,这样也就能实现类似同步执行的情况,看以下示例,在新线程中模拟5s的耗时操作,使用future.get将阻塞等待返回结果。
package demo.thread; 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; public class CallableDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executorService = Executors.newCachedThreadPool(); Future<String> future = executorService.submit(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(5000); return "future result"; } }); System.out.println(System.currentTimeMillis()); System.out.println(future.get()); System.out.println(System.currentTimeMillis()); } }
执行结果如下:
1562077654406
future result
1562077659407
FutureTask间接实现了Runnable和Future接口,同样可以实现上述功能,如下:
package demo.thread; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class FutureTaskDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { FutureTask<String> futureTask = new FutureTask<String>( new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(5000); return "future result"; } }); new Thread(futureTask).start(); System.out.println(System.currentTimeMillis()); System.out.println(futureTask.get()); System.out.println(System.currentTimeMillis()); } }
执行结果如下:
1562077797983
future result
1562077802985