JavaSE---线程-Callable 与 Future
/** * 【Callable 与 Future】 * JDK5开始,Java提供了 Callable接口,Callable接口有个call方法可以作为线程体, * public interface Runnable { * public abstract void run(); * } * * public interface Callable<V> { * V call() throws Exception; * } * * Callable的call方法 与 Runnable的run方法 比较: * 1、call方法有返回值; * 2、call方法可以声明抛出异常; * * Callable接口不是 Runnable的实现类,不能作为 Thread的target; * * JDK5提供了 Future接口 代表 Callable接口的call方法的 返回值; * public interface Future<V> { * // 返回Callable任务的call方法的返回值,将导致 当前线程阻塞,直到子线程结束得到返回值; * V get() throws InterruptedException, ExecutionException; * } * * JDK5提供了 FutureTask类,FutureTask实现了Future接口 且 实现了Runnable接口, FutureTask可以作为Thread的target; * public class FutureTask<V> implements RunnableFuture<V> { * private Callable<V> callable; * * public void run() {} * } * * */ public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask futureTask = new FutureTask(new MyCallable()); Thread thread = new Thread(futureTask); thread.start(); Object o = futureTask.get(); System.out.println(o); } static class MyCallable implements Callable<String>{ @Override public String call() throws Exception { return "MyCallable.call ..."; } }