java并发编程之批量提交线程并获得结果

我们可以使用在jdk1.5加入到J.U.C的Callable,Future实现

代码

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.*;

public class Call {

    public static void main(String[] args) {
        call();
    }

    private static void call() {
        List> callables = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            callables.add(new Callable() {
                @Override
                public String call() throws Exception {
                    return "线程" + Thread.currentThread().getName() + "返回" + UUID.randomUUID();
                }
            });
            //创建线程池
            ExecutorService pool = Executors.newFixedThreadPool(10);
            try {
                List> list = pool.invokeAll(callables);
                for (int j = 0; j < list.size(); j++) {
                    Future future = list.get(j);
                    if (future.isDone()) {
                        System.out.println("执行结果:" + future.get());
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } finally {
                pool.shutdown();
            }
        }
    }
}

你可能感兴趣的:(java并发编程之批量提交线程并获得结果)