zoukankan      html  css  js  c++  java
  • 为何推荐使用线程池而不是显式创建线程原因之一—至少让线程有范围和限制

    下面首先举两个例子来分别展示显式创建线程和使用线程池创建线程:

    显式创建线程:

    package threadLocalDemo;
    
    public class NewThreadDemo {
    
        public static void main(String[] args) {
            for (int i = 0; i < 10; i++) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName());
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }
    }

    结果如下:

    Thread-0
    Thread-3
    Thread-2
    Thread-4
    Thread-6
    Thread-8
    Thread-1
    Thread-7
    Thread-5
    Thread-9

    使用线程池创建线程:

    package threadLocalDemo;
    
    import cn.hutool.core.thread.NamedThreadFactory;
    
    import java.util.concurrent.*;
    
    public class ThreadPoolDemo {
        public static void main(String[] args) {
            ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(11, 20, 5000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(5), new NamedThreadFactory("demo-thread-pool", false), new ThreadPoolExecutor.AbortPolicy());
            for (int i = 0; i < 10; i++) {
                threadPoolExecutor.submit(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName());
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            threadPoolExecutor.shutdown();
        }
    
    }

    结果如下:

    demo-thread-pool1
    demo-thread-pool4
    demo-thread-pool3
    demo-thread-pool2
    demo-thread-pool5
    demo-thread-pool6
    demo-thread-pool7
    demo-thread-pool8
    demo-thread-pool9
    demo-thread-pool10

    1、可以看出如果我们不对显式创建的线程进行命名,跟踪运行情况时将比较混乱,只能看到类似Thread-6这样的名字。

          而使用线程池创建线程,当前线程池创建的线程都有比较统一的命名,是有一定范围的,跟踪运行时比较方便。

    2、另外就是使用线程池天然的就能限制住创建线程的数量,有一定的约束,而显式创建线程是不好控制线程的总数的,比如for循环变成100次,显式创建就会创建100个,而线程池就最多会创建20个(maximumPoolSize属性)。

  • 相关阅读:
    centos7安装ImageMagick
    php安装imagemagick扩展
    php编译安装redis扩展
    springboot和springsecurity使用JWT令牌
    springboot和springsecurity整合OAuth2
    SpringSecurity 整合SpringBoot结合jwt与rsa实现分布式认证授权
    【名额有限】云开发AI拓展能力等你来体验!
    干货:如何借助小程序云开发实现小程序支付功能(含源码)
    云开发数据库又增新技能!
    聚焦“云开发圆桌论坛”,大前端Serverless大佬们释放了这些讯号!
  • 原文地址:https://www.cnblogs.com/silenceshining/p/15596113.html
Copyright © 2011-2022 走看看