實現callable接口的多線程

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( );
}

}
}線程

相關文章
相關標籤/搜索