java线程池之四种线程池详解

四种个线程池之代码解析

2.1 newSingleThreadExecutor

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

/**
 * 核心线程池大小=1
 * 最大线程池大小为1
 * 线程过期时间为0ms
 * LinkedBlockingQueue作为工作队列
 */
public static ExecutorService newSingleThreadExecutor() {
    
    
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}

从参数可以看出来,SingleThreadExecutor 相当于特殊的 FixedThreadPool,它的执行流程如下:

  1. 线程池中没有线程时,新建一个线程执行任务
  2. 有一个线程以后,将任务加入阻塞队列,不停的加
  3. 唯一的这一个线程不停地去队列里取任务执行

总结:SingleThreadExecutor 用于串行执行任务的场景,每个任务必须按顺序执行,不需要并发执行。

2.2 newFixedThreadPool

创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。因为线程池大小为2,每个任务输出index后sleep 2秒,所以每两秒打印。定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()

/**
 * 核心线程池大小=传入参数
 * 最大线程池大小为传入参数
 * 线程过期时间为0ms
 * LinkedBlockingQueue作为工作队列
 */
public static ExecutorService newFixedThreadPool(int nThreads) {
    
    
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

可以看到,FixedThreadPool 的核心线程数和最大线程数都是指定值,也就是说当线程池中的线程数超过核心线程数后,任务都会被放到阻塞队列中。

此外 keepAliveTime 为 0,也就是多余的空余线程会被立即终止(由于这里没有多余线程,这个参数也没什么意义了)。

而这里选用的阻塞队列是 LinkedBlockingQueue,使用的是默认容量 Integer.MAX_VALUE,相当于没有上限。

因此这个线程池执行任务的流程如下:

  1. 线程数少于核心线程数,也就是设置的线程数时,新建线程执行任务
  2. 线程数等于核心线程数后,将任务加入阻塞队列
  3. 由于队列容量非常大,可以一直加
  4. 执行完任务的线程反复去队列中取任务执行

总结: FixedThreadPool 用于负载比较重的服务器,为了资源的合理利用,需要限制当前线程数量。

2.3 newCachedThreadPool

创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程,线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。

/**
 *  核心线程池大小=0
 *  最大线程池大小为Integer.MAX_VALUE
 *  线程过期时间为60s
 *  使用SynchronousQueue作为工作队列
 */
public static ExecutorService newCachedThreadPool() {
    
    
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

可以看到,CachedThreadPool 没有核心线程,非核心线程数无上限,也就是全部使用外包,但是每个外包空闲的时间只有 60 秒,超过后就会被回收。

CachedThreadPool 使用的队列是 SynchronousQueue,这个队列的作用就是传递任务,并不会保存。

因此当提交任务的速度大于处理任务的速度时,每次提交一个任务,就会创建一个线程。极端情况下会创建过多的线程,耗尽 CPU 和内存资源。

它的执行流程如下:

  1. 没有核心线程,直接向 SynchronousQueue 中提交任务
  2. 如果有空闲线程,就去取出任务执行;如果没有空闲线程,就新建一个
  3. 执行完任务的线程有 60 秒生存时间,如果在这个时间内可以接到新任务,就可以继续活下去,否则就拜拜
  4. 由于空闲 60 秒的线程会被终止,长时间保持空闲的 CachedThreadPool 不会占用任何资源。

总结:CachedThreadPool 用于并发执行大量短期的小任务,或者是负载较轻的服务器。

2.4 ScheduledThreadPoolExecutor

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

/**
 * 核心线程池大小=传入参数
 * 最大线程池大小为Integer.MAX_VALUE
 * 线程过期时间为0ms
 * DelayedWorkQueue作为工作队列
 */
public ScheduledThreadPoolExecutor(int corePoolSize) {
    
    
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
          new DelayedWorkQueue());
}

ScheduledThreadPoolExecutor 的执行流程如下:

  1. 添加一个任务
  2. 线程池中的线程从 DelayQueue 中取任务
  3. 然后执行任务

具体执行任务的步骤也比较复杂:

  1. 线程从 DelayQueue 中获取 time 大于等于当前时间的 ScheduledFutureTask
  2. 执行完后修改这个 task 的 time 为下次被执行的时间
  3. 然后再把这个 task 放回队列中

总结:ScheduledThreadPoolExecutor 用于需要多个后台线程执行周期任务,同时需要限制线程数量的场景。

代码展示:

package com.demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolDemo {
    
    

	int i = 0;

	public static void main(String[] args) {
    
    
		ExecutorService singlePool = Executors.newSingleThreadExecutor();
		RunnableService runnableService = new RunnableService("张三" , 5000);
		// Thread t1=new Thread(runnableService);
		singlePool.execute(runnableService);

		ExecutorService fixedPool = Executors.newFixedThreadPool(2);
		ThreadService threadService = new ThreadService("lisi" , 2000);
		// Thread t2=new Thread(threadService);
		fixedPool.execute(threadService);
		fixedPool.execute(runnableService);
		System.out.println("线程执行完毕");

		ExecutorService cachePool = Executors.newCachedThreadPool();
		cachePool.execute(threadService);
		cachePool.execute(runnableService);
		

		ExecutorService schedualPool = Executors.newScheduledThreadPool(5);
		schedualPool.execute(threadService);
		schedualPool.execute(runnableService);
		
	}
}

猜你喜欢

转载自blog.csdn.net/qq_22764659/article/details/111286769