Java中如何创建ThreadFactory时设置线程名称呢?
下文笔者讲述使用ThreadFactory设置线程名称的方法分享,如下所示:
方式一:
例
方式二:
例:
方式三:BasicThreadFactory
例:
当然我们也可用使用java.lang.Thread线程类,对线程名称进行相应的设置
方式一:
使用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);
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。