【问题标题】:meaning of pool number in default name of thread in ScheduledExecutorServiceScheduledExecutorService 中线程默认名称中池号的含义
【发布时间】:2016-11-19 03:05:36
【问题描述】:

我正在使用 ScheduledExecutorService 来维护一个核心大小为 10 的线程池

ScheduledExecutorService 可见性线程池 = Executors.newScheduledThreadPool(10);

现在在日志中我看到 thredName 为 pool-39-thread-3

假设线程号可以从 1 到 10 不等,我对线程号 3 没问题,但是 39 中名称中的池号怎么来?

39 在这里表示什么?请点亮它。

【问题讨论】:

    标签: java multithreading threadpool threadpoolexecutor


    【解决方案1】:

    该字符串是从 java.util.concurrent.Executors$DefaultThreadFactory 初始化的 Thread 对象的名称前缀。

    source code of this class 看起来像

    /**
     * The default thread factory
     */
    static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;
    
        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                                  Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                          poolNumber.getAndIncrement() +
                         "-thread-";
        }
    
        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),
                                  0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }
    

    因此,pool- 后面的数字是从存储在 static 字段中的 AtomicInteger 生成的。每个DefaultThreadFactory 实例都有一个“id”,表示在它之前初始化了多少其他实例(+1)。

    由于Executors 中的大多数ExecutorService 工厂方法都使用了这个DefaultThreadFactory,你也可以假设这个数字代表通过ExecutorService 创建了多少线程池。

    【讨论】:

    • 不是创建了多少线程池;它是创建了多少 DefaultThreadFactory 实例。我不知道为什么 JRE 需要创建 39 个线程工厂,但它可以做到这一点,而不必创建单个线程或单个线程池。
    • 感谢您的回复。在我的应用程序中,我只在应用程序启动时调用了 Executors.newScheduledThreadPool 一次。所以理想情况下它应该显示 pool_1 但我认为我正在使用一些 3rd 方依赖项,例如 datastax 驱动程序、eureka 客户端、嵌入式 tomcat 等,它们可能会创建很多 DefaultThreadFactory 实例。你也有同感吗?
    • @Laxmikant 是的,这很可能是正在发生的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 2014-09-24
    相关资源
    最近更新 更多