Java 线程池

一、什么是线程池?
答:多线程编程不简单,难点在于多线程代码的执行顺序。所以我们把要执行的多线程交给线程池来处理,通过维护一定数量的线程池来达到多个线程的复用。

二、为什么要使用线程池以及线程池的优势?

  1. 降低系统的资源消耗。通过重用已存在的线程,降低线程创建和销毁的损耗。
  2. 提高系统的响应速度。当有任务需要执行时,复用已存在的线程,无需等待新线程的创建便可立即执行。
  3. 方便线程并发数的管控。若是无限制的创建线程,必定会导致内存占用过多和CPU切换过度。(CPU切换的时间成本:需要保持当前执行线程的现场,并恢复要执行线程的线程)
  4. 提供更多强大的功能,延时定时线程池。

三、线程池的执行流程?
在这里插入图片描述
四、如何创建一个线程池?
Java本身提供了工具类 java.util.concurrent.Executors

public ThreadPoolExecutor(int corePoolSize, 
						  int maximumPoolSize, 
						  long keepAliveTime,
						  TimeUnit unit, 
						  BlockingQueue<Runnable> workQueue)
						   {
    this(corePoolSize, maximumPoolSize,
     keepAliveTime, unit, workQueue,
     Executors.defaultThreadFactory(), defaultHandler);
}
  1. corePoolSize(线程池核心大小)
    线程池的核心大小,也可以理解为最小的线程池大小。
    当向线程池提交一个任务时,若线程池已创建的线程数小于corePoolSize,即便此时存在空闲线程,也会通过创建一个新线程来执行该任务,直到已创建的线程数大于或等于corePoolSize。
  2. maximumPoolSize(最大线程池大小)
    线程池所允许的最大线程个数。
    当队列满了,且已创建的线程数小于 maximumPoolSize ,则线程池会创建新的线程来执行任务。
  3. keepAliveTime(线程存活时间)
    当线程池中线程数大于核心线程数时,线程的空闲时间如果超过线程存活时间,那么这个线程就会被销毁,直到线程池中的线程数小于等于核心线程数。
  4. workQueue(任务队列)
    存储等待执行线程的工作队列。
  5. threadFactory(线程工厂)
    用于创建新线程。
    threadFactory 创建的线程也是采用 new Thread() 方式,threadFactory 创建的线程名都具有统一的风格:pool-m-thread-n(m为线程池的编号,n为线程池内的线程编号)。
  6. handler(线程饱和策略)
    当工作队列、线程池全已满时如何拒绝新任务,默认抛出异常。

五、为何使用阻塞队列而不是非阻塞队列?

  1. 阻塞队列可以保证任务队列中没有任务时,阻塞获取任务的线程。使 CPU 进入 wait 状态,并释放 CPU 资源。
  2. 当队列中有任务时,才唤醒对应的线程从队列中取出任务信息去执行。不至于一直占用 CPU 资源。

六、线程池分类
Executors是jdk里面提供的创建线程池的工厂类,它默认提供了4种常用的线程池应用。
1.newFixedThreadPool

  • 固定线程池,核心线程数和最大线程数固定相等,而空闲存活时间为0毫秒,说明此参数也无意义,工作队列为最大为Integer.MAX_VALUE大小的阻塞队列。
  • 当执行任务时,如果线程都很忙,就会丢到工作队列等有空闲线程时再执行,队列满就执行默认的拒绝策略。
 /**
  * Creates a thread pool that reuses a fixed number of threads
  * operating off a shared unbounded queue, using the provided
  * ThreadFactory to create new threads when needed. 
  */
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
}

2.newCachedThreadPool

  • 带缓冲线程池,从构造看核心线程数为0,最大线程数为Integer最大值大小,超过0个的空闲线程在60秒后销毁。
  • SynchronousQueue这是一个直接提交的队列,意味着每个新任务都会有线程来执行,如果线程池有可用线程则执行任务,没有的话就创建一个来执行。
  • 线程池中的线程数不确定,一般建议执行速度较快较小的线程,不然这个最大线程池边界过大容易造成内存溢出。
 /**
  * Creates a thread pool that creates new threads as needed, but
  * will reuse previously constructed threads when they are
  * available.  These pools will typically improve the performance
  * of programs that execute many short-lived asynchronous tasks.
  */
public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
}

3.newSingleThreadExecutor

  • 单线程线程池,核心线程数和最大线程数均为1,空闲线程存活0毫秒同样无意思,意味着每次只执行一个线程,多余的先存储到工作队列,一个一个执行,保证了线程的顺序执行。
/**
 * Creates an Executor that uses a single worker thread operating
 * off an unbounded queue. (Note however that if this single
 * thread terminates due to a failure during execution prior to
 * shutdown, a new one will take its place if needed to execute
 * subsequent tasks.)  Tasks are guaranteed to execute
 * sequentially, and no more than one task will be active at any
 * given time. Unlike the otherwise equivalent
 */
public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}

4.newScheduledThreadPool
调度线程池,即按一定的周期执行任务,即定时任务,对ThreadPoolExecutor进行了包装而已。

/**
 * Creates a thread pool that can schedule commands to run after a
 * given delay, or to execute periodically.
 */
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值