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

java线程之线程池

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

java线程之线程池

 public static void main(String[] args) {
        //创建固定线程池,生产环境不用,会发生OOM
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
        try {
            for (int i = 1; i <=6; i++) {
                int finalI = i;
                fixedThreadPool.execute(() -> {
                    System.out.println("线程名称:" + Thread.currentThread().getName() + ",固定数量:" + finalI);
                });
            }
        } finally {
            fixedThreadPool.shutdown();
        }
        //创建单个线程池,生产环境不用,会发生OOM
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        try {
            for (int i = 1; i <= 6; i++) {
                int finalI = i;
                singleThreadExecutor.execute(() -> {
                    System.out.println("线程名称:" + Thread.currentThread().getName() + ",单个线程:" + finalI);
                });
            }
        } finally {
            fixedThreadPool.shutdown();
        }
        //创建动态线程池,生产环境不用,会发生OOM
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        try {
            for (int i = 1; i <= 6; i++) {
                int finalI = i;
                cachedThreadPool.execute(() -> {
                    System.out.println("线程名称:" + Thread.currentThread().getName() + ",动态线程:" + finalI);
                });
            }
        } finally {
            fixedThreadPool.shutdown();
        }

    }
线程名称:pool-1-thread-1,固定数量:1
线程名称:pool-1-thread-2,固定数量:2
线程名称:pool-1-thread-1,固定数量:3
线程名称:pool-1-thread-2,固定数量:4
线程名称:pool-1-thread-1,固定数量:5
线程名称:pool-1-thread-2,固定数量:6
线程名称:pool-2-thread-1,单个线程:1
线程名称:pool-2-thread-1,单个线程:2
线程名称:pool-2-thread-1,单个线程:3
线程名称:pool-2-thread-1,单个线程:4
线程名称:pool-2-thread-1,单个线程:5
线程名称:pool-2-thread-1,单个线程:6
线程名称:pool-3-thread-1,动态线程:1
线程名称:pool-3-thread-2,动态线程:2
线程名称:pool-3-thread-4,动态线程:4
线程名称:pool-3-thread-3,动态线程:3
线程名称:pool-3-thread-5,动态线程:5
线程名称:pool-3-thread-6,动态线程:6

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

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

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