功能中用到不止一個線程池,出錯的時候很差排查是哪一個池中的線程出錯了,須要給每一個線程命名,參考rt.jar中Executors類中線程池默認命名方式,本身實現了下。java
先貼上源碼ide
/** * 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; } }
demo代碼this
package com.demo.thread.test20170830; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * * @author fsw * */ public class MyThreadFactory implements ThreadFactory{ private static final String DEFAULT_POOL_NAME_PREFIX = "test_pool_"; private final AtomicInteger threadNumber = new AtomicInteger(1); private String pool_name_prefix; public MyThreadFactory() { this.pool_name_prefix = DEFAULT_POOL_NAME_PREFIX; } public MyThreadFactory(String name) { this.pool_name_prefix = name; } @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r, pool_name_prefix + threadNumber.getAndIncrement()); return thread; } }
package com.demo.thread.test20170830; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class Main { public static void main(String[] args) { ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), new MyThreadFactory("this is pool name"), new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { try { if(executor.isShutdown()) { return; } executor.getQueue().put(r); } catch (InterruptedException e) { e.printStackTrace(); } } }); try { for (int i = 0; i < 10; i++) { executor.submit(new Runnable() { @Override public void run() { try { Thread.currentThread().sleep(3000); System.out.println(Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } }); } } finally { executor.shutdown(); } } }
運行結果atom