Executor 框架简介

2018-09-16  本文已影响0人  一路花开_8fab

Executor 框架见下图:

image.png

Executor

Executor是一个基础的接口,其初衷是将任务提交和任务执行细节解耦,下面展示的是其定义的唯一方法。

public interface Executor {

    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the {@code Executor} implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}

ExecutorService

ExecutorService则更加完善,不仅提供生命周期管理的方法,如shutdown等,也提供了更加全面的提交任务机制,如返回Future而不是void的submit方法。

    Future<T> submit(Callable<T> task);

java标准类库提供了几种基础实现,比如ThreadPoolExecutor、ScheduledThreadPoolExecutor ForkJoinPool。这些线程池的设计特点在于其高度的可调节性和灵活性,以尽量满足复杂多变的实际应用场景。

Executors

从简化使用的角度,为我们提供了各种方便的静态工厂方法。常见的几个方法如下:

  1. newFixedThreadPool(int nThreads),重用指定数目(nThreads)的线程,其背后使用的是无界的工作队列
 public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
  1. newSingleThreadExecutor(),它的特点在于工作线程数目被限制为1,操作一个无界的工作队列
  public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

3.newCachedThreadPool(),它是一种用来处理大量短时间工作任务的线程池,它会试图缓存线程并重用,当无缓存线程可用时,就会创建新的工作线程

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

猜你喜欢

热点阅读