Java中如何创建ThreadFactory时设置线程名称呢?

java-教程王 Java经验 发布时间:2022-04-03 09:27:40 阅读数:5282 1
下文笔者讲述使用ThreadFactory设置线程名称的方法分享,如下所示:

方式一:
使用Spring框架的CustomizableThreadFactory

ThreadFactory springThreadFactory = new CustomizableThreadFactory("springThread-pool-");

ExecutorService exec = new ThreadPoolExecutor(1, 1,
		0L, TimeUnit.MILLISECONDS,
		new LinkedBlockingQueue<Runnable>(10),springThreadFactory);
exec.submit(() -> {
	logger.info("--日志");
});

方式二:
使用google guava工具类中的ThreadFactoryBuilder链式方式创建

例:
ThreadFactory guavaThreadFactory = new ThreadFactoryBuilder().setNameFormat("retryClient-pool-").build();

ExecutorService exec = new ThreadPoolExecutor(1, 1,
		0L, TimeUnit.MILLISECONDS,
		new LinkedBlockingQueue<Runnable>(10),guavaThreadFactory );
exec.submit(() -> {
	logger.info("--日志---");
});

方式三:BasicThreadFactory
Apache commons-lang3 提供的 BasicThreadFactory

例:
ThreadFactory basicThreadFactory = new BasicThreadFactory.Builder()
		.namingPattern("basicThreadFactory-").build();

ExecutorService exec = new ThreadPoolExecutor(1, 1,
		0L, TimeUnit.MILLISECONDS,
		new LinkedBlockingQueue<Runnable>(10),basicThreadFactory );
exec.submit(() -> {
	logger.info("--日志---");
});
 

当然我们也可用使用java.lang.Thread线程类,对线程名称进行相应的设置
final Thread thread = new Thread();
thread.setName(name);
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202204/16489493042649.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者