(五)四种线程池底层详解

本专栏多线程目录:

(一)线程是什么

(二)Java线程与系统线程和生命周期

(三)Java线程创建方式

(四)为什么要使用线程池

(五)四种线程池底层详解

(六)ThreadPoolExecutor自定义线程池

(七)线程池的大小如何确定

(八)Callable和Runnable的区别

(九)线程池异常捕获

(十)线程池参数——workQueue用法

(十一)sleep(1)、sleep(0)和sleep(1000)的区别

(十二)yield、notify、notifyAll、sleep、join、wait的区别

(十三)synchronized用法,四种锁范围

(十四)volatile的用法,原子性问题

(十五)ThreadLocal的用法,如何解决内存泄漏

(十六)ReentrantLock可重入锁使用和介绍

(十七)AtomicInteger原子类的介绍和使用

(十八)Worker线程管理


Java中提供了四种线程池创建方法,分别是:

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

1. newSingleThreadExecutor

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

可以看到corePoolSize、maximumPoolSize都是 1 ,keepAliveTime 是 0 ,使用的是LinkedBlockingQueue队列。

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

demo:

public class FourThreadPool {
    public static void main(String[] args) {
ScheduledThreadPoolExecutorTest().ScheduledThreadPoolExecutorTest();
        ExecutorService executorService = new newSingleThreadExecutor().newSingleThreadExecutor();

        for (int i = 0; i < 10; i++) {
            executorService.execute(new TestRunnable());
        }
        executorService.shutdown();
    }

}
class TestRunnable implements Runnable {
    static int i = 1;

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "  线程被调用了。第" + getCount() + "次");
    }
    public static int getCount() {
        return i++;
    }
}
class newSingleThreadExecutor {

    ExecutorService newSingleThreadExecutor() {
        /**
         * 1
         * 此线程池 Executor 只有一个线程。它用于以顺序方式的形式执行任务。
         * 如果此线程在执行任务时因异常而挂掉,则会创建一个新线程来替换此线程,后续任务将在新线程中执行。
         */
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        return executorService;
    }
}

输出:

pool-1-thread-1  线程被调用了。第1次
pool-1-thread-1  线程被调用了。第2次
pool-1-thread-1  线程被调用了。第3次
pool-1-thread-1  线程被调用了。第4次
pool-1-thread-1  线程被调用了。第5次
pool-1-thread-1  线程被调用了。第6次
pool-1-thread-1  线程被调用了。第7次
pool-1-thread-1  线程被调用了。第8次
pool-1-thread-1  线程被调用了。第9次
pool-1-thread-1  线程被调用了。第10次

2. newFixedThreadPool

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

可以看到corePoolSize和maximumPoolSize一样, 由调用者自己设定传入 ,keepAliveTime 是 0 ,使用的是LinkedBlockingQueue队列。

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

可以看到上面两种线程池都是使用了 LinkedBlockingQueue ,而且默认使用的是 new LinkedBlockingQueue<Runnable>());

继续扒一下这个LinkedBlockingQueue 的默认大小

public LinkedBlockingQueue() {
    this(Integer.MAX_VALUE);
}

竟然是 int 类型的最大值

@Native public static final int   MAX_VALUE = 0x7fffffff;

就是说这个队列里面可以放 2^31-1 = 2147483647 个 任务。

demo:

public class FourThreadPool {
    public static void main(String[] args) {
ScheduledThreadPoolExecutorTest().ScheduledThreadPoolExecutorTest();
        ExecutorService executorService = new newFixedThreadPool().newFixedThreadPool();

        for (int i = 0; i < 10; i++) {
            executorService.execute(new TestRunnable());
        }
        executorService.shutdown();
    }

}
class TestRunnable implements Runnable {
    static int i = 1;

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "  线程被调用了。第" + getCount() + "次");
    }
    public static int getCount() {
        return i++;
    }
}
class newFixedThreadPool {
    ExecutorService newFixedThreadPool() {
        /**
         * 2
         * 它是一个拥有固定数量线程的线程池。提交给 Executor 的任务由固定的 n 个线程执行,
         * 如果有更多的任务,它们存储在 LinkedBlockingQueue 里。这个数字 n 通常跟底层处理器CPU支持的线程总数有关。
         */
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        return executorService;
    }
}

输出:

pool-1-thread-1  线程被调用了。第1次
pool-1-thread-2  线程被调用了。第2次
pool-1-thread-2  线程被调用了。第4次
pool-1-thread-2  线程被调用了。第5次
pool-1-thread-2  线程被调用了。第6次
pool-1-thread-2  线程被调用了。第7次
pool-1-thread-1  线程被调用了。第3次
pool-1-thread-1  线程被调用了。第10次
pool-1-thread-2  线程被调用了。第9次
pool-1-thread-3  线程被调用了。第8次

可以看到最多只有3个线程,哪个线程空闲了就执行,超过corePoolSize=3后,任务会被丢到 LinkedBlockingQueue 队列,因为LinkedBlockingQueue很大,所以执行完前面的任务,空闲后会执行队列LinkedBlockingQueue里面的任务。

3. newScheduledThreadPool

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

这里的super还是会调用ThreadPoolExecutor的方法。

可以看到corePoolSize由调用者自己设定传入 ,maximumPoolSize 是int的最大值,keepAliveTime 是 0 ,使用的是DelayedWorkQueue队列。

new DelayedWorkQueue() : 一个按超时时间升序排序的队列,顾名思义,可以延迟执行。

我们可以自定义设置队列的延迟策略:

 * @param command the task to execute
 * @param initialDelay the time to delay first execution
 * @param period the period between successive executions
 * @param unit the time unit of the initialDelay and period parameters
 * @return a ScheduledFuture representing pending completion of
 *         the task, and whose {@code get()} method will throw an
 *         exception upon cancellation
 * @throws RejectedExecutionException if the task cannot be
 *         scheduled for execution
 * @throws NullPointerException if command is null
 * @throws IllegalArgumentException if period less than or equal to zero
 */
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                              long initialDelay,
                                              long period,
                                              TimeUnit unit);

demo:

class ScheduledThreadPoolExecutorTest {

    ScheduledExecutorService ScheduledThreadPoolExecutorTest() {
        /**
         * 3
         * 当我们有一个需要定期运行的任务或者我们希望延迟某个任务时,就会使用此类型的 executor。
         */
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);

        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //创建并执行在给定延迟后启用的单次操作。延迟2秒后启动,但是只执行一次。
        //        executorService.schedule(new TestRunnable(), 2, TimeUnit.SECONDS);
        //延迟2秒后启动,之后每间隔1秒执行一次
        executorService.scheduleAtFixedRate(new TestRunnable(), 2, 1, TimeUnit.SECONDS);

        return executorService;
    }

    public static void main(String[] args) {
        new ScheduledThreadPoolExecutorTest().ScheduledThreadPoolExecutorTest();
    }

}

class TestRunnable implements Runnable {
    static int i = 1;

    @Override
    public void run() {
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        System.out.println(Thread.currentThread().getName() + "  线程被调用了。第" + getCount() + "次");
    }

    public static int getCount() {
        return i++;
    }
}

输出:

2020-07-15 18:03:47
2020-07-15 18:03:49
pool-1-thread-1  线程被调用了。第1次
2020-07-15 18:03:50
pool-1-thread-1  线程被调用了。第2次
2020-07-15 18:03:51
pool-1-thread-2  线程被调用了。第3次
2020-07-15 18:03:52
pool-1-thread-2  线程被调用了。第4次
2020-07-15 18:03:53
pool-1-thread-2  线程被调用了。第5次
2020-07-15 18:03:54
pool-1-thread-2  线程被调用了。第6次
2020-07-15 18:03:55
pool-1-thread-2  线程被调用了。第7次

4. newCachedThreadPool

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

corePoolSize为0;maximumPoolSize为 Integer.MAX_VALUE;keepAliveTime为60L ,单位是秒,使用SynchronousQueue队列。

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

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

demo:

public class FourThreadPool {
    public static void main(String[] args) {
ScheduledThreadPoolExecutorTest().ScheduledThreadPoolExecutorTest();
        ExecutorService executorService = new newCachedThreadPoolTest().newCachedThreadPoolTest();

        for (int i = 0; i < 10; i++) {
            executorService.execute(new TestRunnable());
        }
        executorService.shutdown();
    }

}
class TestRunnable implements Runnable {
    static int i = 1;

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "  线程被调用了。第" + getCount() + "次");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static int getCount() {
        return i++;
    }
}

class newCachedThreadPoolTest {
    ExecutorService newCachedThreadPoolTest() {
        /**
         * 4
         * 此线程池的线程数不受限制。如果所有的线程都在忙于执行任务并且又有新的任务到来了,这个线程池将创建一个新的线程并将其提交到 Executor。
         * 只要其中一个线程变为空闲,它就会执行新的任务。 如果一个线程有 60 秒的时间都是空闲的,它们将被结束生命周期并从缓存中删除。
         */
        ExecutorService executorService = Executors.newCachedThreadPool();
        return executorService;
    }
}

执行结果:

pool-1-thread-2  线程被调用了。第1次
pool-1-thread-1  线程被调用了。第2次
pool-1-thread-3  线程被调用了。第3次
pool-1-thread-4  线程被调用了。第4次
pool-1-thread-5  线程被调用了。第5次
pool-1-thread-6  线程被调用了。第6次
pool-1-thread-7  线程被调用了。第7次
pool-1-thread-8  线程被调用了。第8次
pool-1-thread-9  线程被调用了。第9次
pool-1-thread-10  线程被调用了。第10次

线程池任务执行流程 :

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

参考:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
[JAVA工程师必会知识点之并发编程]1、现在几乎100%的公司面试都必须面试并发编程,尤其是互联网公司,对于并发编程的要求更高,并发编程能力已经成为职场敲门砖。2、现在已经是移动互联和大数据时代,对于应用程序的性能、处理能力、处理时效性要求更高了,传统的串行化编程无法充分利用现有的服务器性能。3、并发编程是几乎所有框架的底层基础,掌握好并发编程更有利于我们学习各种框架。想要让自己的程序执行、接口响应、批处理效率更高,必须使用并发编程。4、并发编程是中高级程序员的标配,是拿高薪的必备条件。 【主讲讲师】尹洪亮Kevin:现任职某互联网公司首席架构师,负责系统架构、项目群管理、产品研发工作。10余年软件行业经验,具有数百个线上项目实战经验。擅长JAVA技术栈、高并发高可用伸缩式微服务架构、DevOps。主导研发的蜂巢微服务架构已经成功支撑数百个微服务稳定运行【推荐你学习这门课的理由:知识体系完整+丰富学习资料】1、 本课程总计122课时,由大体系组成,目的是让你一次性搞定并发编程。分别是并发编程基础、进阶、精通篇、Disruptor高并发框架、RateLimiter高并发访问限流吗,BAT员工也在学。2、课程附带附带3个项目源码,几百个课程示例,5个高清PDF课件。3、本课程0基础入门,从进程、线程、JVM开始讲起,每一个章节只专注于一个知识点,每个章节均有代码实例。 【课程分为基础篇、进阶篇、高级篇】一、基础篇基础篇从进程与线程、内存、CPU时间片轮训讲起,包含线程的3种创建方法、可视化观察线程、join、sleep、yield、interrupt,Synchronized、重入锁、对象锁、类锁、wait、notify、线程上下文切换、守护线程、阻塞式安全队列等内容。二、进阶篇进阶篇课程涵盖volatied关键字、Actomic类、可见性、原子性、ThreadLocal、Unsafe底层、同步类容器、并发类容器、5种并发队列、COW容器、InheritableThreadLocal源码解析等内容。三、精通篇精通篇课程涵盖JUC下的核心工具类,CountDownLath、CyclicBarrier、Phaser、Semaphore、Exchanger、ReentrantLock、ReentrantReadWriteLock、StampedLock、LockSupport、AQS底层、悲观锁、乐观锁、自旋锁、公平锁、非公平锁、排它锁、共享锁、重入锁、线程池、CachedThreadPool、FixedThreadPool、ScheduledThreadPool、SingleThreadExecutor、自定义线程池ThreadFactory、线程池切面编程、线程池动态管理等内容,高并发设计模式,Future模式、Master Worker模式、CompletionService、ForkJoin等课程中还包含Disruptor高并发无锁框架讲解:Disruptor支持每秒600万订单处理的恐怖能力。深入到底层原理和开发模式,让你又懂又会用。高并发访问限流讲解:涵盖木桶算法、令牌桶算法、Google RateLimiter限流开发、Apache JMeter压力测试实战。 【学完后我将达到什么水平?】1、 吊打一切并发编程相关的笔试题、面试题。2、 重构自己并发编程的体系知识,不再谈并发色变。3、 精准掌握JAVA各种并发工具类、方法、关键字的原理和使用。4、 轻松上手写出更高效、更优雅的并发程序,在工作中能够提出更多的解决方案。  【面向人群】1、 总感觉并发编程很难、很复杂、不敢学习的人群。2、 准备跳槽、找工作、拿高薪的程序员。3、 希望提高自己的编程能力,开发出更高效、性能更强劲系统的人群。4、 想要快速、系统化、精准掌握并发编程的人群。【课程知识体系图】

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

醋酸菌HaC

请我喝杯奶茶吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值