线程池—【ThreadPool】—扫盲篇


大家好! 写这篇博客的目的是分析一下线程池的使用,做到知其然知其所以然。
The real target is that I was asked the ThreadPool usage in the interview. And I cann’t answer it.
真正目的是因为在面试中被问到线程池的使用,我没有很好的答上来。

【一】What is the ThreadPool 什么是线程池

  1. 池的概念 :用来放一堆相同东西的容器。eg:水池(装的全是水);水池
  2. 大白话线程池,顾名思义:装的全是线程;
  3. 百度官方说法:在这里插入图片描述
  4. 类比:数据库连接池;
  5. 类图:在这里插入图片描述
  6. 线程池构造方法参数意义:
    在这里插入图片描述

【二】How can we use the ThreadPool 我们如何使用它

1.核心数=最大数 线程无缓存时间 使用LinkedBlockingQueue作为阻塞工作队列的单线程执行器的线程池

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

2.核心数=最大数=n 线程无缓存时间 使用LinkedBlockingQueue作为阻塞工作队列的固定线程执行器的线程池

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

3.核心数=0,最大数=Interger.MAX_VALUE 线程缓存时间=60S 使用SynchronousQueue作为阻塞工作队列的缓存线程执行器的线程池

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

4.核心数=n,最大数=Interger.MAX_VALUE 线程无缓存时间 使用DelayedWorkQueue作为阻塞工作队列的定时任务的线程执行器的线程池

 public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue());
    }

【三】Why use the ThreadPool 为什么使用线程池

1.降低资源消耗:通过重复利用已创建的线程降低线程创建和销毁造成的消耗。

2.提高相应速度:当任务到达时,任务可以不需要等到线程创建就能立即执行。

3.提高线程的可管理性:线程是稀缺资源,如果无限制地创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一分配,调优和监控。

参考资料:
《Java并发编程的技术》
JDK8源码:Executor
JDK8源码:ExecutorService
JDK8源码:AbstractExecutorService
JDK8源码:ThreadPoolExecutor
JDK8源码:Executors
JDK8源码:ScheduledThreadPoolExecutor

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值