callable异步
1.任务结束后能够提供一个返回值ide
2.其中的call方法能够抛出异常测试
3.运行callable能够拿到一个Future对象,Future对象表示异步计算的结果,他提供了检查计算是否完成的方法。spa
实现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; } }
测试code
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()方法会返回结果对象