一起学JAVA之【基础篇】4种默认线程池介绍

一起学JAVA之【基础篇】4种默认线程池介绍

默认线程池创建方式

java.util.concurrent 提供了一个创建线程池的工具类Executors,里面有四种常用的线程池创建方法

public class DemoThreadPool{
    public static void main(String[] args){
        //创建一个核心线程数和最大线程数相同的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        executorService.execute(()->{System.out.println("this is fixed thread pool");});
        //创建一个单线程的线程池
        ExecutorService singleExecutor = Executors.newSingleThreadExecutor();
        singleExecutor.execute(() -> System.out.println("this is single thread pool"));
        //创建一个缓存线程池
        ExecutorService cacheExecutor = Executors.newCachedThreadPool();
        cacheExecutor.execute(()-> System.out.println("this is cache thread pool"));
        //创建一个延时执行任务的线程池
        ScheduledExecutorService scheduleExecutor = Executors.newScheduledThreadPool(4);
        scheduleExecutor.schedule(()-> System.out.println("this is schedule thread 	pool"),2,TimeUnit.SECONDS);
    }
}

接下来我们来看一下他们的特点

线程池名称使用阻塞队列特点
newFixedThreadPoolLinkedBlockingQueue()1、核心线程数和最大线程数相同
2、由于keepAliveTime设置为0,当线程创建后会一直存在
3、由于用的是无界队列所以可能会导致OOM
newSingleThreadExecutorLinkedBlockingQueue()1、核心线程数和最大线程数都为1单线程
2、无界队列可能导致OOM
newCachedThreadPoolSynchronousQueue()1、核心线程数为0,最大线程数为Integer.MAX_VALUE
2、当没任务时线程存活时间为60秒
3、使用的是0大小的队列,所以不存储任务,只做任务转发
newScheduledThreadPoolnew DelayedWorkQueue()1、执行周期任务
2、无界队列,可能会导致OOM

从上面可以看出他们各有各的特点,但是阿里巴巴开发守则却不推荐使用以上线程池,因为它们可能会对服务资源的浪费,所以推荐使用通过ThreadPoolExecutor自定线程池。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值