给线程池里面线程添加名称的4种方式

2年前 (2022) 程序员胖胖胖虎阿
237 0 0

给线程池里面线程添加名称的4种方式

  • 1、 Spring 框架提供的 CustomizableThreadFactory
  • 2、Google guava 工具类 提供的 ThreadFactoryBuilder ,使用链式方法创建。
  • 3、 Apache commons-lang3 提供的 BasicThreadFactory
  • 4、 自定义一个ThreadFactory

1、 Spring 框架提供的 CustomizableThreadFactory

private ThreadFactory springThreadFactory = new CustomizableThreadFactory("springThread-pool-");
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
								10, 
								30, 
								5, 
								TimeUnit.MINUTES, 
								new ArrayBlockingQueue<Runnable>(1000),
								springThreadFactory ); //给线程池中的线程自定义名称

2、Google guava 工具类 提供的 ThreadFactoryBuilder ,使用链式方法创建。

private ThreadFactory guavaThreadFactory = new ThreadFactoryBuilder().setNameFormat("retryClient-pool-").build();
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
								10, 
								30, 
								5, 
								TimeUnit.MINUTES, 
								new ArrayBlockingQueue<Runnable>(1000),
								guavaThreadFactory ); //给线程池中的线程自定义名称

3、 Apache commons-lang3 提供的 BasicThreadFactory

private ThreadFactory basicThreadFactory = new BasicThreadFactory.Builder().namingPattern("basicThreadFactory-").build();
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
								10, 
								30, 
								5, 
								TimeUnit.MINUTES, 
								new ArrayBlockingQueue<Runnable>(1000),
								basicThreadFactory ); //给线程池中的线程自定义名称

4、 自定义一个ThreadFactory

自定义NamesThreadFactory 代码:

public class NamesThreadFactory implements ThreadFactory{
	
	private final ThreadGroup group;
	private final AtomicInteger threadNumber = new AtomicInteger(1);
	private final String namePrefix;

	public NamesThreadFactory(String name) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        if (null == name || name.isEmpty()) {
            name = "pool";
        }
        namePrefix = name + "-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;
    }

}

使用代码

private NamesThreadFactory namesThreadFactory = new NamesThreadFactory("namesThread-");
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
								10, 
								30, 
								5, 
								TimeUnit.MINUTES, 
								new ArrayBlockingQueue<Runnable>(1000),
								namesThreadFactory); //给线程池中的线程自定义名称

出自:
1、Java线程池中三种方式创建 ThreadFactory 设置线程名称
2、线程池自定义线程名字

版权声明:程序员胖胖胖虎阿 发表于 2022年9月21日 下午7:40。
转载请注明:给线程池里面线程添加名称的4种方式 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...