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.DiscardOldestPolicy());
CompletionService completionService = new ExecutorCompletionService(tpe);
//存储线程的返回值
List<Future<String>> results = new LinkedList<Future<String>>();
for (int i = 0; i < 100; i++) {
Task task = new Task(i);
System.out.println(Thread.currentThread().getName()+"放入线程池:" + i);
//调用submit可以获得线程的返回值
Future<String> result = tpe.submit(task);
results.add(result);
}
// for (int i = 0; i < 20; i++) {
// Task task = new Task(i);
// System.out.println(Thread.currentThread().getName()+"放入线程池:" + i);
// completionService.submit(task);
//
// }
//此函数表示不再接收新任务,
//如果不调用,awaitTermination将一直阻塞
tpe.shutdown();
//1小时,模拟等待
// System.out.println(tpe.awaitTermination(1, TimeUnit.HOURS));
System.out.println("输出");
// 输出结果
for (int i = 0; i < 100; i++) {
System.out.println("======"+results.get(i).get());
}
// for (int i = 0; i < 20; i++) {
// System.out.println("======"+completionService.take().get());
// }
}
private class Task implements Callable {
private int val;
public Task(int val) {
this.val = val;
}
@Override
public String call() throws Exception {
try {
if(val == 5){
Thread.sleep(1000);
}else {
Thread.sleep(10);
System.out.println("等待100ms");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("完成 "+ val);
return "返回值" + val;
}
}
}
使用Future result = tpe.submit(task);是先执行完任务在返回,按顺序来。
CompletionService completionService = new ExecutorCompletionService(tpe);用这个是谁执行完直接返回。
大家可以自行调试。