Java四种线程池的使用

    技术2022-07-10  163

    Java四种线程池的使用

    Java通过Executors提供四种线程池,分别为:

    newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

    四种线程池的使用详细

    1、newCachedThreadPool 线程池

    创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

    创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,那么就会回收部分空闲(60秒不执行任务)的线程。当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。 public static void main(String[] args) { ExecutorService pool= Executors.newCachedThreadPool(); for (int i = 1; i <= 10; i++) { final int num = i; if (i==5){ try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } pool.execute(() -> { System.out.println("线程名称:" + Thread.currentThread().getName() + ",执行" + num); }); } }

    输出日志:

    线程名称:pool-1-thread-1,执行1 线程名称:pool-1-thread-2,执行2 线程名称:pool-1-thread-3,执行3 线程名称:pool-1-thread-4,执行4 线程名称:pool-1-thread-3,执行6 线程名称:pool-1-thread-4,执行5 线程名称:pool-1-thread-2,执行7 线程名称:pool-1-thread-3,执行9 线程名称:pool-1-thread-4,执行8 线程名称:pool-1-thread-1,执行10

    通俗:当有新任务到来,则插入到SynchronousQueue中,由于SynchronousQueue是同步队列,因此会在池中寻找可用线程来执行,若有可以线程则执行,若没有可用线程则创建一个线程来执行该任务;若池中线程空闲时间超过指定大小,则该线程会被销毁。

    适用:执行很多短期异步的小程序或者负载较轻的服务器

    线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。

    底层代码:

    调用方法:

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

    其中:0表示初始线程池中线程个数为零;Integer.MAX_VALUE表示线程池中最大的线程个数;60L表示线程的存活时间,当线程数大于内核数时,这是多余的空闲线程在终止之前等待新任务的最长时间;TimeUnit.SECONDS表示线程存活时间的单位为秒;

    构造方法:

    public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); }

     

    public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }

    2、newFixedThreadPool 线程池

    创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

    创建固定大小的线程池。每次提交一个任务就创建一个线程,直到线程达到线程池的最大大小线程池的大小一旦达到最大值就会保持不变,如果某个线程因为执行异常而结束,那么线程池会补充一个新线程 public static void main(String[] args) { ExecutorService pool= Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { final int num = i; pool.execute(() -> { System.out.println("线程名称:" + Thread.currentThread().getName() + ", 执行 " + num ); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } }); } }

    输出日志:

    线程名称:pool-1-thread-1, 执行 0 线程名称:pool-1-thread-2, 执行 1 线程名称:pool-1-thread-4, 执行 3 线程名称:pool-1-thread-3, 执行 2 线程名称:pool-1-thread-5, 执行 4 线程名称:pool-1-thread-1, 执行 5 线程名称:pool-1-thread-3, 执行 6 线程名称:pool-1-thread-4, 执行 7 线程名称:pool-1-thread-2, 执行 8 线程名称:pool-1-thread-5, 执行 9

    通俗:创建可容纳固定数量线程的池子,每隔线程的存活时间是无限的,当池子满了就不在添加线程了;如果池中的所有线程均在繁忙状态,对于新任务会进入阻塞队列中(无界的阻塞队列)。

    适用:执行长期的任务,性能好很多。

    底层代码:

    调用方法:

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

    其中:nThreads表示线程池中线程的数量,返回线程池时,已经在线程池中创建好了这些线程。0L表示存活时间,当线程数大于内核数时,这是多余的空闲线程在终止之前等待新任务的最长时间;TimeUnit.SECONDS表示线程存活时间的单位为秒;

    构造方法:

    public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); }

     

    public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }

    3、newScheduledThreadPool 线程池

    创建一个可定期或者延时执行任务的定长线程池,支持定时及周期性任务执行。

    public static void main(String[] args) { ScheduledExecutorService pool=Executors.newScheduledThreadPool(5); Runnable r1 = () -> System.out.println("线程名称:" + Thread.currentThread().getName() + ",执行:3秒后执行"); pool.schedule(r1, 3, TimeUnit.SECONDS); Runnable r2 = () -> System.out.println("线程名称:" + Thread.currentThread().getName() + ",执行:延迟2秒后每3秒执行一次"); pool.scheduleAtFixedRate(r2, 2, 3, TimeUnit.SECONDS); Runnable r3 = () -> System.out.println("线程名称:" + Thread.currentThread().getName() + ",执行:普通任务"); for (int i = 0; i < 5; i++) { pool.execute(r3); } }

    输出日志:

    线程名称:pool-1-thread-1,执行:普通任务 线程名称:pool-1-thread-1,执行:普通任务 线程名称:pool-1-thread-1,执行:普通任务 线程名称:pool-1-thread-1,执行:普通任务 线程名称:pool-1-thread-1,执行:普通任务 线程名称:pool-1-thread-1,执行:延迟2秒后每3秒执行一次 线程名称:pool-1-thread-2,执行:3秒后执行 线程名称:pool-1-thread-3,执行:延迟2秒后每3秒执行一次 线程名称:pool-1-thread-3,执行:延迟2秒后每3秒执行一次 线程名称:pool-1-thread-3,执行:延迟2秒后每3秒执行一次 线程名称:pool-1-thread-3,执行:延迟2秒后每3秒执行一次 ******(一直输出上面的语句)

    通俗:创建一个固定大小的线程池,线程池内线程存活时间无限制,线程池可以支持定时及周期性任务执行,如果所有线程均处于繁忙状态,对于新任务会进入DelayedWorkQueue队列中,这是一种按照超时时间排序的队列结构。

    适用:周期性执行任务的场景。

    底层代码:

    调用方法:

    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); }

     

    public class ScheduledThreadPoolExecutor extends ThreadPoolExecutor implements ScheduledExecutorService{ //dosomething...... public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue()); } //dosomething...... }

     

    public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); }

     

    public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }

     

    4、newSingleThreadExecutor 线程池

    创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行.

    public static void main(String[] args) { ExecutorService pool= Executors.newSingleThreadExecutor(); for (int i = 0; i < 5; i++) { final int num= i; pool.execute(() -> System.out.println(Thread.currentThread().getName() + "=>" + num)); } }

    输出日志:

    pool-1-thread-1=>0 pool-1-thread-1=>1 pool-1-thread-1=>2 pool-1-thread-1=>3 pool-1-thread-1=>4

    通俗:创建只有一个线程的线程池,且线程的存活时间是无限的;当该线程正繁忙时,对于新任务会进入阻塞队列中(无界的阻塞队列)

    适用:一个任务一个任务执行的场景

    底层代码:

    调用方法:

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

     

    static class FinalizableDelegatedExecutorService extends DelegatedExecutorService { FinalizableDelegatedExecutorService(ExecutorService executor) { super(executor); } protected void finalize() { super.shutdown(); } }

     

    线程池任务执行流程:

    当线程池小于corePoolSize时,新提交任务将创建一个新线程执行任务,即使此时线程池中存在空闲线程。当线程池达到corePoolSize时,新提交任务将被放入workQueue中,等待线程池中任务调度执行当workQueue已满,且maximumPoolSize>corePoolSize时,新提交任务会创建新线程执行任务当提交任务数超过maximumPoolSize时,新提交任务由RejectedExecutionHandler处理当线程池中超过corePoolSize线程,空闲时间达到keepAliveTime时,关闭空闲线程当设置allowCoreThreadTimeOut(true)时,线程池中corePoolSize线程空闲时间达到keepAliveTime也将关闭

    备注:

      一般如果线程池任务队列采用LinkedBlockingQueue队列的话,那么不会拒绝任何任务(因为队列大小没有限制),这种情况下,ThreadPoolExecutor最多仅会按照最小线程数来创建线程,也就是说线程池大小被忽略了。如果线程池任务队列采用ArrayBlockingQueue队列的话,那么ThreadPoolExecutor将会采取一个非常负责的算法,比如假定线程池的最小线程数为4,最大为8所用的ArrayBlockingQueue最大为10。随着任务到达并被放到队列中,线程池中最多运行4个线程(即最小线程数)。即使队列完全填满,也就是说有10个处于等待状态的任务,ThreadPoolExecutor也只会利用4个线程。如果队列已满,而又有新任务进来,此时才会启动一个新线程,这里不会因为队列已满而拒接该任务,相反会启动一个新线程。新线程会运行队列中的第一个任务,为新来的任务腾出空间。这个算法背后的理念是:该池大部分时间仅使用核心线程(4个),即使有适量的任务在队列中等待运行。这时线程池就可以用作节流阀。如果挤压的请求变得非常多,这时该池就会尝试运行更多的线程来清理;这时第二个节流阀—最大线程数就起作用了。

    Processed: 0.011, SQL: 9