【问题标题】:How to add prefix in thread names generated through ExecutorService如何在通过 ExecutorService 生成的线程名称中添加前缀
【发布时间】:2020-09-11 15:41:10
【问题描述】:

我有 jdk 1.7 的 java 代码,如下所示,它正在执行并行线程基础实现

ExecutorService executorService = Executors.newFixedThreadPool(currentRecordSize); executorService.execute((Runnable) someobject);

在日志中我得到了类似的线程名称

pool-2-thread-1 池 2 线程 2 池 1 线程 1 pool-1-thread-2

我想用一些字符串作为后缀

【问题讨论】:

标签: java multithreading executorservice


【解决方案1】:

您可以使用自定义线程工厂,例如在 Ehcache 中就有这样一种实现方式:

public class NamedThreadFactory implements ThreadFactory {

    private static AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    /**
     * Constructor accepting the prefix of the threads that will be created by this {@link ThreadFactory}
     * 
     * @param namePrefix
     *            Prefix for names of threads
     */
    public NamedThreadFactory(String namePrefix) {
        this.namePrefix = namePrefix;
    }

    /**
     * Returns a new thread using a name as specified by this factory {@inheritDoc}
     */
    public Thread newThread(Runnable runnable) {
        return new Thread(runnable, namePrefix + " thread-" + threadNumber.getAndIncrement());
    }

}

然后你可以这样创建你的执行器:

ExecutorService executor = Executors.newFixedThreadPool(currentRecordSize, new NamedThreadFactory("Your prefix here"));

【讨论】:

  • 我可以设置私有静态 AtomicInteger threadNumber = new AtomicInteger(1);作为实例方法,因为这是在某种后台作业中完成的,这将根据基于工厂的计数进行设置。
  • 我在我的回答中给出了详细信息(仅供参考)。请建议它是否有意义。我基本上是一个 C# 活跃的开发人员,十年前做过 java 开发。所以需要一点帮助
  • 是的,当然,threadNumber 可以是实例变量而不是静态字段,这只是一个示例。
【解决方案2】:

我的代码带有@Guillaume 逻辑。我唯一在想的是 AtomicInteger 字段应该是类级别而不是静态的,因为在每个循环之后根据我的逻辑创建新池

public void run() {
        log.info(name + " Started");
        ExecutorService executorService = null;
        
        while (true) {
            try {
                
                List<HashMap<String, String>> rows = QueryFromDB;
                int currentRecordSize = rows.size();                
                if (currentRecordSize > 0) {
                    NamedThreadFactory threadFactory = new NamedThreadFactory(name);
                    log.info(" *** " + name + " Initializing Executor . Received " + rows.size() + " txns.");
                    if (currentRecordSize < threadPoolSize) {
                        //executorService = Executors.newFixedThreadPool(currentRecordSize);
                        executorService = Executors.newFixedThreadPool(currentRecordSize, threadFactory);
                    } else {
                        //executorService = Executors.newFixedThreadPool(threadPoolSize);
                        executorService = Executors.newFixedThreadPool(threadPoolSize, threadFactory);
                    }
                    for (HashMap<String, String> row : rows) {
                                   MyClass obj = fromsomeclassmethod;
                                    if (obj instanceof Runnable) {
                                        executorService.execute((Runnable) obj);
                                    } else {
                                        obj.SomeMethod(..);
                                    }
                                    Thread.sleep(ThreadExecutorSleep);//some minor sleep like 10 miliseconds                                
                    }

                    if (!(executorService.isShutdown())) {
                        executorService.shutdown();
                        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
                    }
                }                
                Thread.sleep(ADMSProcessor.fetchQueInterval);//1 second  sleep
            } catch (Exception ex) {
                log.fatal("Exception in " + name + " Thread :" + ex);
            }
        }
    }




public class NamedThreadFactory implements ThreadFactory {

    //private static AtomicInteger threadNumber = new AtomicInteger(1);
    private AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    /**
     * Constructor accepting the prefix of the threads that will be created by this {@link ThreadFactory}
     *
     * @param namePrefix
     *            Prefix for names of threads
     */
    public NamedThreadFactory(String namePrefix) {
        this.namePrefix = namePrefix;
    }

    /**
     * Returns a new thread using a name as specified by this factory {@inheritDoc}
     */
    public Thread newThread(Runnable runnable) {
        return new Thread(runnable, namePrefix + " thread-" + threadNumber.getAndIncrement());
    }
}

【讨论】:

    猜你喜欢
    • 2012-06-18
    • 2014-09-29
    • 2020-01-05
    • 2011-09-01
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    相关资源
    最近更新 更多