四类线程池对象

67 阅读1分钟
  1. 固定大小的线程池工厂,没有救急线程
public static ExecutorService newFixedThreadPool(int nThreads) {
   return new ThreadPoolExecutor(nThreads, nThreads,
                                 0L, TimeUnit.MILLISECONDS,
                                 new LinkedBlockingQueue<Runnable>());
}

在代码中可以看到,核心线程数等于总的线程数,因此这个线程池对象没有救急线程,于此同时,注意到这个线程工厂的阻塞队列是没有容量限制的。

  1. 只有救急线程,没有常驻线程
public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

在这个方法可以看出,常驻线程数被设置为0。而总的线程数被设置为MAX_VALUE。注意到这个阻塞队列是SynchronousQueue类型。这个类型的队列,只有有人取,才会有人往里面放,因此队列容量为0. 3. 仅仅只有单个线程

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

在这个代码中和固定大小的线程池一样,但是外面被这个AutoShutdownDelegatedExecutorService类进行了修饰,这个修饰主要是为了把以前的对象转换到别的类型上去,进而可以使得这个对象不对外暴露一些方法,例如修改核心线程数等。这个单例是真正意义上的单例,不会被篡改。 4. 可以延迟执行的线程池

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE,
          DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
          new DelayedWorkQueue());
}

在代码中可以看出依然是ThreadPoolExecutor这个类不同的是,里面用了一个DelayWorkQueue()这个阻塞队列。 在应用中的时候调用schedule方法进行延迟执行。

scheduleWithFixedDelay()

这个方法是可以以一个固定的peroid连续执行

scheduleWithFixedDelay()

这个方法是相较于上一次延时多久执行下一次。