Future 和 FutureTask用於接收callable的返回值

lichuangcsdn發表於2018-06-30

例子如下:

package com.company.demo1;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadTask {

    public static void main(String[] args) throws Exception {
        Task1 task1 = new Task1();
        Task2 task2 = new Task2();
        Task3 task3 = new Task3();
        List<Callable<String>> taskList = Arrays.asList(task1,task2,task3);

        ExecutorService executorService = Executors.newFixedThreadPool(3);

        //提交單個任務
        Future<String> taskFuture = executorService.submit(task1);

        //批量提交任務
        List<Future<String>> futureList = executorService.invokeAll(taskList);

        for (Future<String> future : futureList) {
            //獲取執行緒返回的結果
            String result = future.get(); //此語句會一直阻塞到結果完成

            System.out.println(result);
        }
        executorService.shutdown();
    }
}

class Task1 implements Callable<String> {

    @Override
    public String call() {
        System.out.println("執行緒Task1 開始執行");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("執行緒Task1 結束執行");
        return "1111";
    }
}

class Task2 implements Callable<String> {

    @Override
    public String call() {
        System.out.println("執行緒Task2 開始執行");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("執行緒Task2 結束執行");
        return "2222";
    }
}

class Task3 implements Callable<String> {

    @Override
    public String call() {
        System.out.println("執行緒Task3 開始執行");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("執行緒Task3 結束執行");
        return "3333";
    }
}

相關文章