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

How to add prefix in thread names generated through ExecutorService

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

ExecutorService executorService = Executors.newFixedThreadPool(currentRecordSize); executorService.execute((可运行) someobject);

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

pool-2-thread-1 池 2 线程 2 池 1 线程 1 池 1 线程 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 字段应该是 class 级别而不是静态的,因为在每个循环之后根据我的逻辑创建新池

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());
    }
}