Java ExecutorService 多線程實踐(一),executorservice

來源:互聯網
上載者:User

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 控制也是可以實現的。




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.