Spring 框架提供的
CustomizableThreadFactory
。
1 ThreadFactory springThreadFactory = new CustomizableThreadFactory("springThread-pool-");
4 ExecutorService exec = new ThreadPoolExecutor(1, 1,
5 0L, TimeUnit.MILLISECONDS,
6 new LinkedBlockingQueue<Runnable>(10),springThreadFactory);
7 exec.submit(() -> {
8 logger.info("--记忆中的颜色是什么颜色---");
9 });
2. ThreadFactoryBuilder
Google guava 工具类 提供的
ThreadFactoryBuilder
,使用链式方法创建。
1 ThreadFactory guavaThreadFactory = new ThreadFactoryBuilder().setNameFormat("retryClient-pool-").build();
4 ExecutorService exec = new ThreadPoolExecutor(1, 1,
5 0L, TimeUnit.MILLISECONDS,
6 new LinkedBlockingQueue<Runnable>(10),guavaThreadFactory );
7 exec.submit(() -> {
8 logger.info("--记忆中的颜色是什么颜色---");
9 });
3. BasicThreadFactory
Apache commons-lang3 提供的
BasicThreadFactory
.
1 ThreadFactory basicThreadFactory = new BasicThreadFactory.Builder()
2 .namingPattern("basicThreadFactory-").build();
4 ExecutorService exec = new ThreadPoolExecutor(1, 1,
5 0L, TimeUnit.MILLISECONDS,
6 new LinkedBlockingQueue<Runnable>(10),basicThreadFactory );
7 exec.submit(() -> {
8 logger.info("--记忆中的颜色是什么颜色---");
9 });
4. 三种方式总结
最终本质都是 给 java.lang.Thread#name 设置名称,详情源码感兴趣的可以自行查看。
1 final Thread thread = new Thread();
2 thread.setName(name);