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

例子如下:

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> taskList = Arrays.asList(task1,task2,task3);

        ExecutorService executorService = Executors.newFixedThreadPool(3);

        //提交单个任务
        Future taskFuture = executorService.submit(task1);

        //批量提交任务
        List> futureList = executorService.invokeAll(taskList);

        for (Future future : futureList) {
            //获取线程返回的结果
            String result = future.get(); //此语句会一直阻塞到结果完成

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

class Task1 implements Callable {

    @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 {

    @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 {

    @Override
    public String call() {
        System.out.println("线程Task3 开始运行");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程Task3 结束运行");
        return "3333";
    }
}

你可能感兴趣的:(java多线程)