Executors - 969251639/study GitHub Wiki

Executors可以用来快速构造出线程池,一般主要有以下三种方式构建

  1. newFixedThreadPool:生成固定大小的线程池
  2. newSingleThreadExecutor:生成只有一个线程的线程池
  3. newCachedThreadPool:生成可动态伸缩的线程池
public class Executors {
    ...
    //生成固定大小的线程池,其中核心线程数和最大线程数都是一样的,阻塞队列用LinkedBlockingQueue,几乎无限大,有OOM风险
    public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }

    //生成只有一个线程的线程池,其中核心线程数和最大线程数都是1,阻塞队列用LinkedBlockingQueue,几乎无限大,有OOM风险
    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
    public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>(),
                                    threadFactory));
    }

    //生成可动态伸缩的线程池,其中核心线程数是0,最大线程数都是int的最大值(2147483647),阻塞队列用SynchronousQueue,线程池几乎可以无限扩大,SynchronousQueue并不缓存任务,线程数可以在0和2147483647直接动态伸缩,有OOM风险,一般不用
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
    public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>(),
                                      threadFactory);
    }
    ...
}

Executors还有很多其他有用的方法,以后分析补上

⚠️ **GitHub.com Fallback** ⚠️