Callable 对象实际上属于Executor框架的功能类,callable接口和runable接口相似,可是提供了比runnable更增强大的功能,主要表现为一下3点:
1 callable能够在任务结束的时候提供一个返回值,runnable没法提供这个功能。
2 callable中的call()方法能够抛出异常,而runnable不能。
3 运行callable能够拿到一个future对象,而future对象表示异步计算的结果,它提供了检查运算是否结束的方法,因为线程属于异步计算模型,因此没法从其余线程中获得方法的返回值,在这种状况之下,就能够使用future来监视目标线程调用call方法的状况,当调用future的get方法以获取结果时,当前线程就会被阻塞,直到call方法结束返回结果。框架
public class MyCallBack {异步
public static void main ( String[] args ) {ide
ExecutorService threadPool = Executors.newSingleThreadExecutor(); // 启动线程 Future<String> stringFuture = threadPool.submit( new Callable< String >( ) { @Override public String call ( ) throws Exception { return "nihao"; } } ); try { System.out.println( stringFuture.get() ); } catch ( InterruptedException e ) { e.printStackTrace( ); } catch ( ExecutionException e ) { e.printStackTrace( ); }
}
}线程