常见线程池的具体用法

本文介绍了线程池的概念,探讨了使用线程池的原因,并详细讲解了ThreadPoolExecutor、FixedThreadPool、ScheduledThreadPool、CachedThreadPool和SingleThreadExecutor五种线程池的用法和特点,包括各自的创建方法、参数意义及应用场景。
摘要由CSDN通过智能技术生成

1. 什么是线程池?

线程池其实就是将多个线程对象放到一个容器当中。

2. 为什么使用线程池?

可以重用线程,减少创建和销毁线程带来的消耗。

3.线程池的工作原理?

4. 如何使用线程池?

要想知道如何使用线程池,就要先知道线程池的种类有多少种?线程池大概有以下几种:

  1. ThreadPoolExecutor
  2. FixedThreadPool
  3. CahcedThreadPool
  4. SingleThreadExecutor
  5. ScheduledThreadPool

以下介绍这几种线程池的用法:

3.1 ThreadPoolExecutor

ThreadPoolExecutor 是线程池真正的实现方法,以下是 ThreadPoolExecutor 的构造方法:

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) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         threadFactory, defaultHandler);
}
 
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          RejectedExecutionHandler handler) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), handler);
}
 
public ThreadPoolExecutor(int corePoolS
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值