java线程池序号(pool-X-thread-Y中,X的值)持续增长的问题

java线程池序号(pool-X-thread-Y中,X的值)持续增长的问题

问题描述:

代码如下

 public static void multiThread(List<Integer> list) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(list.size());
        CountDownLatch countDownLatch = new CountDownLatch(list.size());//线程等待参数,等待次数为集合数量

        list.stream().<Runnable>map(s -> () -> {
            try {
                Thread.sleep(1000);
                System.out.println(s + "||||" + Thread.currentThread().getName());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();//每执行完一个线程,等待计数器减一
            }
        }).forEach(pool::execute);
        countDownLatch.await();//当所有线程都工作完毕时,再进行下一步
        pool.shutdown();
    }


    public static void main(String[] args) throws InterruptedException {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        while (true) {
            multiThread(list);
        }
    }

打印出来的东西如下:

5||||pool-1-thread-5
1||||pool-1-thread-1
3||||pool-1-thread-3
4||||pool-1-thread-4
2||||pool-1-thread-2
1||||pool-2-thread-1
2||||pool-2-thread-2
3||||pool-2-thread-3
5||||pool-2-thread-5
4||||pool-2-thread-4
1||||pool-3-thread-1
2||||pool-3-thread-2
3||||pool-3-thread-3
4||||pool-3-thread-4
5||||pool-3-thread-5
5||||pool-4-thread-5
2||||pool-4-thread-2
4||||pool-4-thread-4
3||||pool-4-thread-3
1||||pool-4-thread-1
1||||pool-5-thread-1
5||||pool-5-thread-5
4||||pool-5-thread-4
2||||pool-5-thread-2
3||||pool-5-thread-3

 

可以看出pool-后面的线程池序号是在不断增长的,即使执行了shutdown()方法,这个对于实际的程序运行会不会有什么坏的影响?如何让线程池数量不变呢?框架为springboot
 

你在创建线程池的时候没有定义线程工厂,使用的自然是默认的。默认实现是

  DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                                  Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                          poolNumber.getAndIncrement() +
                         "-thread-";
        }

序号自然是依次递增的,在java.util.concurrent.Executors.DefaultThreadFactory 这个内部类里面。不想递增也可以,可以自己定义一个ThreadFactory,传递进去就行了,框架提供方法了

public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory)

把threadFactory传进来就行,名字咋命名,全看你喽~