hzk11o11k11o 2021-04-20 15:07 采纳率: 30%
浏览 464
已采纳

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
 

  • 写回答

1条回答 默认 最新

  • 笔下天地宽 2021-04-20 15:50
    关注

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

      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传进来就行,名字咋命名,全看你喽~

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致