自定義線程池的名稱(ThreadPoolExecutor)

目的:有時候爲了快速定位出現錯誤的位置,在採用線程池時咱們須要自定義線程池的名稱。ide

一、建立ThreadFactory(ThreadPoolExecutor默認採用的是DefaultThreadFactory,能夠參照代碼)。測試

public class NamedThreadFactory implements ThreadFactory{

        private final AtomicInteger poolNumber = new AtomicInteger(1);

        private final ThreadGroup threadGroup;

        private final AtomicInteger threadNumber = new AtomicInteger(1);

        public  final String namePrefix;

        NamedThreadFactory(String name){
            SecurityManager s = System.getSecurityManager();
            threadGroup = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            if (null==name || "".equals(name.trim())){
                name = "pool";
            }
            namePrefix = name +"-"+
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(threadGroup, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

二、建立線程池spa

 
//核心線程滿了,則進入隊列,隊列滿了,則建立新線程,當線程數達到最大線程數,則進入拒絕策略
static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5,5,1,
            TimeUnit.MINUTES,new LinkedBlockingDeque<>(),new NamedThreadFactory("測試"));

三、測試代碼線程

 static ThreadLocal<SimpleDateFormat>threadLocal = new ThreadLocal<SimpleDateFormat>(){
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };


 public static void main(String[] args) {
        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(threadLocal.get().parse("2019-10-22 16:59:00"));
                    throw new NullPointerException("sfa");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });
    }

四、結果code

相關文章
相關標籤/搜索