java中獲取線程返回值的幾種方式

在之前的工作中,主要是寫業(yè)務(wù)代碼,線程使用得很少,也沒有考慮執(zhí)行線程后如何獲取返回值的問題,而線程中的run()方法是沒有返回值的。那如果在線程執(zhí)行完畢后想要獲取對(duì)應(yīng)的值要怎么做?借著最近的學(xué)習(xí)總結(jié)一下。線程返回值主要有幾種方式。

  1. 通過代碼做循環(huán)判斷
  2. 使用join
  3. 使用Callable接口和FutureTask
  4. 使用線程池

下面通過demo做一下演示

public class MyThreadReturn implements Runnable {
    /** 模擬線程執(zhí)行完畢后主程序要獲取的值*/
    private String returnValue;
    @Override
    public void run() {
        System.out.println("線程執(zhí)行......");
        /** 模擬IO*/
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("線程執(zhí)行完畢......");
        returnValue = "hello world!!!";
    }
    public String getReturnValue(){
        return returnValue;
    }

    public static void main(String[] args) {
        MyThreadReturn myThreadReturn = new MyThreadReturn();
        Thread thread = new Thread(myThreadReturn);
        thread.start();
        System.out.println(myThreadReturn.getReturnValue());
    }
}

以上代碼因?yàn)镸yThreadReturn線程需要5秒執(zhí)行完畢,主線程中并不能順利獲取到returnValue

null
線程執(zhí)行.....

將代碼做如下修改

通過循環(huán)判斷

該方法本質(zhì)是自己控制業(yè)務(wù)邏輯

public static void main(String[] args) throws InterruptedException {
        MyThreadReturn myThreadReturn = new MyThreadReturn();
        Thread thread = new Thread(myThreadReturn);
        thread.start();
        /** 通過while循環(huán)判斷*/
        while (myThreadReturn.getReturnValue() == null){
            Thread.sleep(1000);
        }
        System.out.println(myThreadReturn.getReturnValue());
    }

使用join

使用join方法可以讓子線程執(zhí)行完畢后再執(zhí)行主線程,本質(zhì)和通過循環(huán)判斷一樣

public static void main(String[] args) throws InterruptedException {
        MyThreadReturn myThreadReturn = new MyThreadReturn();
        Thread thread = new Thread(myThreadReturn);
        thread.start();
        /** 使用join*/
        thread.join();
        System.out.println(myThreadReturn.getReturnValue());
    }

使用Callable接口和FutureTask

代碼如下,通過FutureTask的get()方法獲取返回值

public class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        System.out.println("線程執(zhí)行......");
        Thread.sleep(5000);
        System.out.println("線程執(zhí)行完畢......");
        return "hello world!!!";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
        /***
         * futureTask 實(shí)現(xiàn)了 Runnable接口
         * 所以新建線程的時(shí)候可以傳入futureTask
         * FutureTask重寫的run方法中實(shí)際是調(diào)用了Callable接口在call()方法
         * 所以執(zhí)行線程的時(shí)候回執(zhí)行call方法的內(nèi)容
         */
        Thread thread = new Thread(futureTask);
        thread.start();
        String value = futureTask.get();
        System.out.println(value);
    }
}

使用線程池

public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<String> submit = executorService.submit(new MyCallable());
        System.out.println(submit.get());
    }

以上代碼返回值均為

線程執(zhí)行......
線程執(zhí)行完畢......
hello world!!!
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 進(jìn)程和線程 進(jìn)程 所有運(yùn)行中的任務(wù)通常對(duì)應(yīng)一個(gè)進(jìn)程,當(dāng)一個(gè)程序進(jìn)入內(nèi)存運(yùn)行時(shí),即變成一個(gè)進(jìn)程.進(jìn)程是處于運(yùn)行過程中...
    勝浩_ae28閱讀 5,256評(píng)論 0 23
  • Java-Review-Note——4.多線程 標(biāo)簽: JavaStudy PS:本來是分開三篇的,后來想想還是整...
    coder_pig閱讀 1,761評(píng)論 2 17
  • Android Handler機(jī)制系列文章整體內(nèi)容如下: Android Handler機(jī)制1之ThreadAnd...
    隔壁老李頭閱讀 4,407評(píng)論 2 12
  • 一、并發(fā) 進(jìn)程:每個(gè)進(jìn)程都擁有自己的一套變量 線程:線程之間共享數(shù)據(jù) 1.線程 Java中為多線程任務(wù)提供了很多的...
    SeanMa閱讀 2,802評(píng)論 0 11
  • 于我看來,人是由感性和理性組成的。理性的現(xiàn)實(shí)意義高于感性,但人總會(huì)被一時(shí)迸發(fā)出的感性操控。我是極不喜歡這樣的,這種...
    長風(fēng)雅閱讀 544評(píng)論 0 4

友情鏈接更多精彩內(nèi)容