如何使用线程池去执行多个任务并且获取任务执行后的结果

代码如下

package com.thread.threadlocal;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;

public class MainTest {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Set> callableSet = new HashSet<>();
        callableSet.add(() -> "task1");
        callableSet.add(() -> "task2");
        callableSet.add(() -> "task3");
        List> list = executorService.invokeAll(callableSet);
        for(Future stringFuture : list) {
            System.out.println("future task: " + stringFuture.get());
        }
        TimeUnit.MILLISECONDS.sleep(500);
        executorService.shutdown();
    }

}

执行结果如下

future task: task2
future task: task1
future task: task3

你可能感兴趣的:(并发)