package com.test; import java.util.LinkedList; import java.util.List; import java.util.concurrent.*; public class ThreadPoolExecutorTest2 { public static void main(String[] args) throws InterruptedException, ExecutionException{ ThreadPoolExecutorTest2 threadPoolExecutorTest2 = new ThreadPoolExecutorTest2(); threadPoolExecutorTest2.doThing(); } public void doThing() throws InterruptedException, ExecutionException { /** * 创建线程池,并发量最大为5 * LinkedBlockingDeque,表示执行任务或者放入队列 */ ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 10, 0, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy()); //存储线程的返回值 List<Future<String>> results = new LinkedList<Future<String>>(); for (int i = 0; i < 10; i++) { Task task = new Task(i); System.out.println("放入线程池:" + i); //调用submit可以获得线程的返回值 Future<String> result = tpe.submit(task); results.add(result); } //此函数表示不再接收新任务, //如果不调用,awaitTermination将一直阻塞 tpe.shutdown(); //1小时,模拟等待 System.out.println(tpe.awaitTermination(1, TimeUnit.HOURS)); //输出结果 for (int i = 0; i < 10; i++) { System.out.println(results.get(i).get()); } } private class Task implements Callable { private int val; public Task(int val) { this.val = val; } @Override public String call() throws Exception { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("完成 "+ val); return "返回值" + val; } } }
运行结果:
放入线程池:0
放入线程池:1
放入线程池:2
放入线程池:3
放入线程池:4
放入线程池:5
放入线程池:6
放入线程池:7
放入线程池:8
放入线程池:9
完成 0
完成 1
完成 3
完成 2
完成 4
完成 5
完成 6
完成 9
完成 7
完成 8
true
返回值0
返回值1
返回值2
返回值3
返回值4
返回值5
返回值6
返回值7
返回值8
返回值9