一、 整体框架

Excutors是工具类,提供很多便捷的工厂方法。
image.png

image.png

二、 使用流程

1、创建线程对象

实现Runnable接口重写run方法 或者 Callable 并重写 call方法。
两个实现方法的区别是,后者可以有返回结果。

  1. public class RuntimeCallable implements Callable<Object>{
  2. public String name;
  3. public RuntimeCallable(int i){
  4. this.name = "thread-"+i;
  5. }
  6. public Object call() throws Exception {
  7. Date start = new Date();
  8. Random random = new Random();
  9. Thread.sleep(random.nextInt(1000));
  10. Date end = new Date();
  11. return end.getTime() - start.getTime();
  12. }
  13. }

2、创建线程池

可以创建 ThreadPoolExecutor对象构建线程池,调用execute或者submit方法把 任务加入到线程中去。

  1. int taskSize = 5;
  2. ExecutorService pool = Executors.newFixedThreadPool(5);
  3. List<Future> futureList = new ArrayList();
  4. for(int i=0; i<taskSize; i++){
  5. Callable c = new RuntimeCallable(i);
  6. Future f = pool.submit(c);
  7. futureList.add(f);
  8. }

3、调用Future对象的get方法获取结果,并关闭线程池

  1. pool.shutdown();
  2. for(Future f : futureList){
  3. System.out.println(f.get());
  4. }

参考:

https://blog.csdn.net/tongdanping/article/details/79604637