当前位置: 移动技术网 > IT编程>开发语言>Java > 【转】创建线程以及线程池时候要指定与业务相关的名字,以便于追溯问题

【转】创建线程以及线程池时候要指定与业务相关的名字,以便于追溯问题

2018年08月28日  | 移动技术网IT编程  | 我要评论

原文:https://www.jianshu.com/p/d6245f2c3a9d

3.9 创建线程以及线程池时候要指定与业务相关的名字,以便于追溯问题

日常开发中当一个应用中需要创建多个线程或者线程池时候最好给每个线程或者线程池根据业务类型设置具体的名字,以便在出现问题时候方便进行定位,下面就通过实例来说明不设置时候为何难以定位问题,以及如何进行设置。

3.9.1创建线程需要带线程名

下面通过简单的代码来说明不指定线程名称为何难定位问题,代码如下:

 public static void main(string[] args) {
       //订单模块
        thread threadone = new thread(new runnable() {
            public void run() {
                system.out.println("保存订单的线程");
                try {
                    thread.sleep(500);
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
                throw new nullpointerexception();
            }
        });
     //发货模块
        thread threadtwo = new thread(new runnable() {
            public void run() {
                system.out.println("保存收获地址的线程");
            }
        });

        threadone.start();
        threadtwo.start();

    }

 

如上代码分别创建了线程one和线程two并且启动执行运行上面代码可能会输出如下:

 

image.png

从运行接口可知thread-0抛出了npe异常,那么单看这个日志根本无法判断是订单模块的线程抛出的异常,首先我们分析下这个thread-0是怎么来的,这要看下创建线程时候的代码:

 public thread(runnable target) {
        init(null, target, "thread-" + nextthreadnum(), 0);
    }
    private void init(threadgroup g, runnable target, string name,
                      long stacksize) {
        init(g, target, name, stacksize, null);
    }

 

可知如果调用了没有指定线程名字的方法创建了线程,内部会使用"thread-" + nextthreadnum()作为线程的默认名字,其中nextthreadnum代码如下:

  private static int threadinitnumber;
    private static synchronized int nextthreadnum() {
        return threadinitnumber++;
    }

 

可知threadinitnumber是static变量,nextthreadnum是static方法,所以线程的编号是全应用唯一的并且是递增的,另外这里由于涉及到了多线程递增threadinitnumber也就是执行读取-递增-写入操作,而这个是线程不安全的所以使用了方法级别的synchronized进行同步。

当一个系统中有多个业务模块而每个模块中有都是用了自己的线程,除非抛出与业务相关的异常,否者比如上面抛出的npe异常,根本没法判断是哪一个模块出现了问题,现在修改代码如下:

  static final string thread_save_order = "thread_save_order";
    static final string thread_save_addr = "thread_save_addr";

    public static void main(string[] args) {
        // 订单模块
        thread threadone = new thread(new runnable() {
            public void run() {
                system.out.println("保存订单的线程");
                throw new nullpointerexception();
            }
        }, thread_save_order);
        // 发货模块
        thread threadtwo = new thread(new runnable() {
            public void run() {
                system.out.println("保存收货地址的线程");
            }
        }, thread_save_addr);

        threadone.start();
        threadtwo.start();

    }

 

如上代码在创建线程的时候给线程指定了一个与具体业务模块相关的名字,下面运行结果输出为:

 

image.png

从运行结果就可以定位到是保存订单模块抛出了npe异常,一下子就可以定位到问题。

3.9.2创建线程池时候也需要指定线程池的名称

同理下面通过简单的代码来说明不指定线程池名称为何难定位问题,代码如下:

static threadpoolexecutor executorone = new threadpoolexecutor(5, 5, 1, timeunit.minutes, new linkedblockingqueue<>());
    static threadpoolexecutor executortwo = new threadpoolexecutor(5, 5, 1, timeunit.minutes, new linkedblockingqueue<>());

    public static void main(string[] args) {

        //接受用户链接模块
        executorone.execute(new  runnable() {
            public void run() {
                system.out.println("接受用户链接线程");
                throw new nullpointerexception();
            }
        });
        //具体处理用户请求模块
        executortwo.execute(new  runnable() {
            public void run() {
                system.out.println("具体处理业务请求线程");
            }
        });
        
        executorone.shutdown();
        executortwo.shutdown();
    }

 

运行代码输出如下结果:


同理我们并不知道是那个模块的线程池抛出了这个异常,那么我们看下这个pool-1-thread-1是如何来的。其实是使用了线程池默认的threadfactory,翻看线程池创建的源码如下:

    public threadpoolexecutor(int corepoolsize,
                              int maximumpoolsize,
                              long keepalivetime,
                              timeunit unit,
                              blockingqueue<runnable> workqueue) {
        this(corepoolsize, maximumpoolsize, keepalivetime, unit, workqueue,
             executors.defaultthreadfactory(), defaulthandler);
    }
    
   public static threadfactory defaultthreadfactory() {
   return new defaultthreadfactory();
    }
    

 static class defaultthreadfactory implements threadfactory {
        //(1)
        private static final atomicinteger poolnumber = new atomicinteger(1);
        private final threadgroup group;
        //(2)
        private final atomicinteger threadnumber = new atomicinteger(1);
        //(3)
        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) {
           //(4)
            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;
        }
    }

 

如上代码defaultthreadfactory的实现可知:

  • 代码(1)poolnumber是static的原子变量用来记录当前线程池的编号是应用级别的,所有线程池公用一个,比如创建第一个线程池时候线程池编号为1,创建第二个线程池时候线程池的编号为2,这里pool-1-thread-1里面的pool-1中的1就是这个值
  • 代码(2)threadnumber是线程池级别的,每个线程池有一个该变量用来记录该线程池中线程的编号,这里pool-1-thread-1里面的thread-1中的1就是这个值
  • 代码(3)nameprefix是线程池中线程的前缀,默认固定为pool
  • 代码(4)具体创建线程,可知线程的名称使用nameprefix + threadnumber.getandincrement()拼接的。

从上知道我们只需对实现threadfactory并对defaultthreadfactory的代码中nameprefix的初始化做手脚,当需要创建线程池是传入与业务相关的nameprefix名称就可以了,代码如下:

 // 命名线程工厂
    static class namedthreadfactory 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;

        namedthreadfactory(string name) {

            securitymanager s = system.getsecuritymanager();
            group = (s != null) ? s.getthreadgroup() : thread.currentthread().getthreadgroup();
            if (null == name || name.isempty()) {
                name = "pool";
            }

            nameprefix = name + "-" + 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;
        }
    }

 

然后创建线程池时候如下:

   static threadpoolexecutor executorone = new threadpoolexecutor(5, 5, 1, timeunit.minutes,
            new linkedblockingqueue<>(), new namedthreadfactory("asyn-accept-pool"));
    static threadpoolexecutor executortwo = new threadpoolexecutor(5, 5, 1, timeunit.minutes,
            new linkedblockingqueue<>(), new namedthreadfactory("asyn-process-pool"));

 

然后运行执行结果如下:

image.png

asyn-accept-pool-1-thread-1就可以知道是接受链接线程池抛出的异常。

3.9.3总结

本节通过简单的例子介绍了为何不给线程或者线程池起名字会给问题排查带来麻烦,然后通过源码原理介绍线程和线程池名称是默认名称是如何来的,以及如何自定义线程池名称,以便问题追溯。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网