生命周期:
ExecutorService扩展了Executor并添加了一些生命周期管理的方法。一个Executor的生命周期有三种状态,运行 ,关闭 ,终止 。
Executor创建时处于运行状态。当调用ExecutorService.shutdown()后,处于关闭状态,isShutdown()方法返回true。
这时,不应该再想Executor中添加任务,所有已添加的任务执行完毕后,Executor处于终止状态,isTerminated()返回true。
public class Excutors_2 { public static void main(String[] args) { ExecutorService es = Executors.newCachedThreadPool(); es.shutdown(); try { es.execute(new Runnable(){ public void run() { System.out.println("i my run!"); } }); }catch(RejectedExecutionException e){ System.out.println("ExecutorService is shutdown!"); } } }
取异步值:
ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,返回Future。
如果Executor后台线程池还没有完成Callable的计算,这调用返回Future对象的get()方法,会阻塞直到计算完成。
public class Excutors_3 { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService es = Executors.newCachedThreadPool(); try { Future<String> f = es.submit(new Callable<String>(){ public String call() throws Exception { TimeUnit.SECONDS.sleep(10L); // do something..2 return "2.resulet"; } }); //"do something..1. String result = "1.result"; System.out.println("--- result ---"); System.out.println(result + " and " +f.get()); System.out.println("--- end ---"); }catch(RejectedExecutionException e){ System.out.println("ExecutorService is shutdown!"); }finally{ es.shutdown(); } } }