簡體   English   中英

如何在通過 ExecutorService 生成的線程名稱中添加前綴

[英]How to add prefix in thread names generated through ExecutorService

我有 jdk 1.7 的 java 代碼,如下所示,它正在執行並行線程基礎實現

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

在日志中,我得到了線程名稱,例如

pool-2-thread-1 pool-2-thread-2 pool-1-thread-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());
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM