JAVA 筆記 Callable 與 FutureTask:有傳回值的多線程

來源:互聯網
上載者:User

          常用的Thread類在run方法執行完之後是沒有傳回值的,要實現子線程完成任務後傳回值給主線程需要藉助第三方轉存。Callable介面則提供了一種有傳回值的多線程實現方法。下面以一個簡單的地主、監工和長工的例子展示這種介面的用法。

長工類:

長工類實現了Callable介面,線程運行完成後返回一個Integer值。

import java.util.concurrent.Callable;

public class Changgong implements Callable<Integer>{

    private int hours=12;
    private int amount;
    
    @Override
    public Integer call() throws Exception {
        while(hours>0){
            System.out.println("I'm working......");
            amount ++;
            hours--;
            Thread.sleep(1000);
        }
        return amount;
    }
}

 

 地主:主進程

監工:FutureTask

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Dizhu {
        
    public static void main(String args[]){
        Changgong worker = new Changgong();
        FutureTask<Integer> jiangong = new FutureTask<Integer>(worker);
        new Thread(jiangong).start();
        while(!jiangong.isDone()){
            try {
                System.out.println("看長工做完了沒...");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        int amount;
        try {
            amount = jiangong.get();
            System.out.println("工作做完了,上交了"+amount);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }
}

 運行結果:

看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
工作做完了,上交了12

 

 從上面的例子可以看出,FutureTask 扮演了一個監工的角色,地主(主進程)通過不斷地詢問監工(isDone()方法)可以得知長工的工作是否完成,並且在長工完成工作後讓監工收取成果(get()方法)。

 

聯繫我們

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