如何在通过ExecutorService生成的线程名称中添加前缀

问题描述

我有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

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

解决方法

您可以使用自定义线程工厂,例如在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"));
,

我的代码具有@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());
    }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...