自定义线程工厂:
public class CustomThreadFactory implements ThreadFactory { private static final Logger LOGGER = LoggerFactory.getLogger(CustomThreadFactory.class); public static Thread.UncaughtExceptionHandler LOGGER_UNCAUGHT_EXCEPTION_HANDLER = (t, e) -> LOGGER.error(t.getName(), e); private static final AtomicInteger poolNumber = new AtomicInteger(1); private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; private CustomThreadFactory(ThreadGroup group, String prefix) { if (group == null) { SecurityManager s = System.getSecurityManager(); this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); } else { this.group = group; } if (prefix == null) { this.namePrefix = "custom-" + poolNumber.getAndIncrement() + "-thread-"; } else { this.namePrefix = prefix + "-pool_" + poolNumber.getAndIncrement() + "-thread-"; } } public CustomThreadFactory(String prefix) { this(null, prefix); } @Override public Thread newThread(Runnable r) { // 线程组中活跃的线程数// this.group.activeCount(); Thread t = new Thread(this.group, r, this.namePrefix + this.threadNumber.getAndIncrement(), 0); t.setDaemon(true); t.setUncaughtExceptionHandler(LOGGER_UNCAUGHT_EXCEPTION_HANDLER); if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; }}
单例模式自定义线程池:
public class MyAsyncExecutor extends ThreadPoolExecutor { private static final Logger LOGGER = LoggerFactory.getLogger(MyAsyncExecutor.class); private MyAsyncExecutor() { super(Runtime.getRuntime().availableProcessors() * 5, 500, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue<>(1000), new CustomThreadFactory("MyAsync"), (r, e) -> LOGGER.error("{}", e.getActiveCount())); } public static MyAsyncExecutor instance() { return Holder.INSTANCE; } private static class Holder { private static MyAsyncExecutor INSTANCE = new MyAsyncExecutor(); }}