0%

Executor框架

Executor框架

Executor框架的结构

主要由3部分组成

  • 任务:任务需要实现Runnable接口或者Callable接口
  • 任务的执行:核心接口
    • Executor
      • ExecutorService
        • ThreadPoolExecutor
        • ScheduledThreadExecutor
  • 异步计算的结果
    • Future
      • FutureTask

Executor框架的成员

主要成员有:ThreadPoolExecutor,ScheduledThreadExecutor,Future,Runnable,Callable,Executors

ThreadPoolExecutor

三种工厂类创建

  • Executors.FixedThreadPool(),创建使用固定线程数的FixedThreadPool的API,适用于满足资源管理的需要,限制当前线程数量的应用场景,负载比较重的服务器
  • SingleThreadExecutor:创建单个线程的SingleThreadExecutor 的API。适用于保证顺序执行各个人物,并且在任意时间点,不会有多个线程是活动的场景
  • CachedThreadPool:是大小无界的线程,适用于执行很多短期异步任务的小程序。或者负载轻的服务器。

ScheduledThreadPoolExecutor

  • ScheduledThreadPoolExecutor:包含若干个线程的ScheduledThreadPoolExecutor
  • SingleThreadScheduledExecutor:只包含一个线程。适用于单个线程周期执行,顺序执行的场景

Future接口

FutureTask用来表示异步的结果

Runnable和Callable

他们之间的区别在于Runnable不会返回结果,Callable可以返回结果

ThreadPoolExecutor详解

他是线程池的实现类。主要有四部分组成

  • corePool:核心线程数大小
  • maximumPool:最大线程池的大小
  • BlockingQueue:用来暂时保存任务的工作队列
  • RejectExecutionHandler:当executor关闭或饱和时,executor方法奖要调用的handler

FixedThreadPool

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

注意这里的队列没有设置容量,所以是无界队列。

SingleThreadExecutor

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

注意这里的线程数设置为1。

CachedThreadPool

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

这里核心线程数设置为0,最大线程数是无界的,如果主线程提交任务的速度高于处理任务的速度,则会不断创建线程,极端条件下会导致内存溢出

ScheduledThreadPoolExecutor

主要用来给定延迟之后运行任务,或者定期执行任务

public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }

DelayQueue是一个无界队列,封装了一个PriorityQueue,会对ScheduledFutureTask进行排序,time小的放前面(先执行)。

~~