callable
1.任務結束后可以提供一個返回值
2.其中的call方法可以拋出異常
3.運行callable可以拿到一個Future對象,Future對象表示異步計算的結果,他提供了檢查計算是否完成的方法。
實現Callable接口
public class Main implements Callable{ int i; @Override public Object call() throws Exception { String str=null; for (i=0;i<100;i++){ str=Thread.currentThread().getName()+"--"+i; System.out.println(str); } return str; } }
測試
public class Client { public static void main(String[] args) { ExecutorService threadPool= Executors.newSingleThreadExecutor(); Future<String> future=threadPool.submit(new Main()); System.out.println("----------"); try { System.out.println(future.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
線程結束后,future.get()方法會返回結果