Java中使用有傳回值的線程

來源:互聯網
上載者:User

標籤:pool   檢測   sub   lse   stack   The   exec   ==   阻塞   

在建立多線程程式的時候,我們常實現Runnable介面,Runnable沒有傳回值,要想獲得傳回值,Java5提供了一個新的介面Callable,可以擷取線程中的傳回值,但是擷取線程的傳回值的時候,需要注意,我們的方法是非同步,擷取傳回值的時候,線程任務不一定有傳回值,所以,需要判斷線程是否結束,才能夠去取值。

測試代碼
package com.wuwii.test;import java.util.concurrent.*;/** * @author Zhang Kai * @version 1.0 * @since <pre>2017/10/31 11:17</pre> */public class Test {    private static final Integer SLEEP_MILLS = 3000;    private static final Integer RUN_SLEEP_MILLS = 1000;    private int afterSeconds = SLEEP_MILLS / RUN_SLEEP_MILLS;    // 線程池(根據機器的核心數)    private final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());    private void testCallable() throws InterruptedException {        Future<String> future = null;        try {            /**             * 在建立多線程程式的時候,我們常實現Runnable介面,Runnable沒有傳回值,要想獲得傳回值,Java5提供了一個新的介面Callable             *             * Callable需要實現的是call()方法,而不是run()方法,傳回值的類型有Callable的型別參數指定,             * Callable只能由ExecutorService.submit() 執行,正常結束後將返回一個future對象。             */            future = fixedThreadPool.submit(() -> {                Thread.sleep(SLEEP_MILLS);                return "The thread returns value.";            });        } catch (Exception e) {            e.printStackTrace();        }        if (future == null) return;        for (;;) {            /**             * 獲得future對象之前可以使用isDone()方法檢測future是否完成,完成後可以調用get()方法獲得future的值,             * 如果直接調用get()方法,get()方法將阻塞到線程結束,很浪費。             */            if (future.isDone()) {                try {                    System.out.println(future.get());                    break;                } catch (InterruptedException | ExecutionException e) {                    e.printStackTrace();                }            } else {                System.out.println("After " + afterSeconds-- + " seconds,get the future returns value.");                Thread.sleep(1000);            }        }    }    public static void main(String[] args) throws InterruptedException {        new Test().testCallable();    }}

運行結果:

After 3 seconds,get the future returns value.After 2 seconds,get the future returns value.After 1 seconds,get the future returns value.The thread returns value.
總結:
  1. 需要傳回值的線程使用Callable 介面,實現call 方法;
  2. 獲得future對象之前可以使用isDone()方法檢測future是否完成,完成後可以調用get()方法獲得future的值,如果直接調用get()方法,get()方法將阻塞到線程結束。

Java中使用有傳回值的線程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.