Java ExecutorService 多線程實踐(一),executorservice
需要實現一個多線程並發的業務情境,啟動若干子線程,最後要所有子線程運行結束才結束。(類似 .NET 裡的 Task WaitAll )
Java 中的 ExecutorService 多線程編程模型提供這樣一個機制,通過代碼來介紹一下。
方法一:ExecutorService#awaitTermination
/** * Blocks until all tasks have completed execution after a shutdown * request, or the timeout occurs, or the current thread is * interrupted, whichever happens first. * * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @return <tt>true</tt> if this executor terminated and * <tt>false</tt> if the timeout elapsed before termination * @throws InterruptedException if interrupted while waiting */ boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
通過 ExecutorService#submit(或者execute) 加入子線程並啟動,awaitTermination 阻塞等待所有子線程執行完畢。
sample:
ExecutorService es = Executors.newCachedThreadPool();List<Future<String>> futureList = Lists.newArrayList();futureList.add(es.submit(new Callable<String>() {@Overridepublic String call() throws Exception {System.out.println("Threading1 is running");Thread.sleep(1000);return "1";}}));futureList.add(es.submit(new Callable<String>() {@Overridepublic String call() throws Exception {System.out.println("Threading2 is running");Thread.sleep(3000);return "2";}}));futureList.add(es.submit(new Callable<String>() {@Overridepublic String call() throws Exception {System.out.println("Threading3 is running");Thread.sleep(2000);return "3";}}));es.shutdown();try {boolean completed = es.awaitTermination(2000, TimeUnit.MILLISECONDS);System.out.println("all tasks completed: " + completed);//es.wait(3000);for(Future future : futureList) {try {if (future.isDone()) {System.out.println("result: " + future.get());}} catch (CancellationException ex) {ex.printStackTrace();} finally {future.cancel(true);}}} catch (Exception e) {e.printStackTrace();}
輸出結果:
Threading 1 is runningThreading 2 is runningThreading 3 is runningall tasks completed: falseresult: 1result: 3
只有1和3輸出了結果,因為 awaitTermination 逾時設定了 2000 ms,Threading2 類比了 3000 ms 因此被逾時取消了。通過 Future#isDone() 可以判斷對應線程是否處理完畢,
這個情境裡如果 isDone() == false 那麼就可以認為是被逾時幹掉了。
需要注意的是,在添加完所有的子線程並啟動後調用了 ExecutorService#shutdown 方法:一方面是不再接受新的子線程"提交",另一方面ExecutorService 其實自己也是一個work線程,如果不shutdown 其實當前線程並不會結束。調用shutdown 和不調用shutdown 從main運行後控制台狀態就可以看出差異。
最後在 finally 裡調用了 Future#cancel() 主要是當await之後,被逾時處理的線程可能還在運行,直接取消掉。
方法二:ExecutorService#invokeAll
invokeAll 很像上述實現的整體封裝,但細節略有不同。首先將 Callable 統一建立好放在List裡交給 invokeAll 方法執行並設定逾時時間。
ExecutorService es = Executors.newCachedThreadPool();List<Callable<String>> tasks = Lists.newArrayList();tasks.add(new Callable<String>() {@Overridepublic String call() throws Exception {System.out.println("Threading 1 is running");Thread.sleep(1000);return "1";}});tasks.add(new Callable<String>() {@Overridepublic String call() throws Exception {System.out.println("Threading 2 is running");Thread.sleep(3000);return "2";}});tasks.add(new Callable<String>() {@Overridepublic String call() throws Exception {System.out.println("Threading 3 is running");Thread.sleep(2000);return "3";}});try {List<Future<String>> futureList = es.invokeAll(tasks, 2000, TimeUnit.MILLISECONDS);es.shutdown();for(Future future : futureList) {try {if (future.isDone()) {System.out.println("result: " + future.get());}} catch (CancellationException ex) {ex.printStackTrace();}}} catch (Exception e) {e.printStackTrace();}輸出結果:
Threading 1 is runningThreading 2 is runningThreading 3 is runningresult: 1result: 3java.util.concurrent.CancellationException
ExecutorService#invokeAll() 執行後所有 future.isDone() 都是 true,在 future.get() 拿結果的時候,被逾時的Future會拋出 CancellationException 。因為在 invokeAll 內部調用了Future#cancel() 方法。
源碼如下:
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { if (tasks == null || unit == null) throw new NullPointerException(); long nanos = unit.toNanos(timeout); List<Future<T>> futures = new ArrayList<Future<T>>(tasks.size()); boolean done = false; try { for (Callable<T> t : tasks) futures.add(newTaskFor(t)); long lastTime = System.nanoTime(); // Interleave time checks and calls to execute in case // executor doesn't have any/much parallelism. Iterator<Future<T>> it = futures.iterator(); while (it.hasNext()) { execute((Runnable)(it.next())); long now = System.nanoTime(); nanos -= now - lastTime; lastTime = now; if (nanos <= 0) return futures; } for (Future<T> f : futures) { if (!f.isDone()) { if (nanos <= 0) return futures; try { f.get(nanos, TimeUnit.NANOSECONDS); } catch (CancellationException ignore) { } catch (ExecutionException ignore) { } catch (TimeoutException toe) { return futures; } long now = System.nanoTime(); nanos -= now - lastTime; lastTime = now; } } done = true; return futures; } finally { if (!done) for (Future<T> f : futures) f.cancel(true); } }
當然在 ExecutorService 編程模型外,自己定義Threading,通過CountDownLatch 控制也是可以實現的。