栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

一起学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自定线程池。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/397244.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号