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

huangapple go评论72阅读模式
英文:

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

我想要在它们后面添加一些字符串。

英文:

I have java code with jdk 1.7 like following which is doing parallel thread base implementation

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

In logs i am getting thread name like

pool-2-thread-1
pool-2-thread-2
pool-1-thread-1
pool-1-thread-2

I wanted to suffix them with some string

答案1

得分: 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"));
英文:

You can use a custom thread factory, for instance in Ehcache there's one implemented this way:

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

}

Then you can create your executor this way:

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

答案2

得分: 0

以下是您提供的代码的翻译部分:

public void run() {
    log.info(name + " 已启动");
    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 + " 正在初始化执行器。接收到 " + rows.size() + " 个交易。");
                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); //一些小的睡眠,比如 10 毫秒
                }

                if (!(executorService.isShutdown())) {
                    executorService.shutdown();
                    executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
                }
            }                
            Thread.sleep(ADMSProcessor.fetchQueInterval); //1 秒的休眠
        } catch (Exception ex) {
            log.fatal(name + " 线程中出现异常:" + ex);
        }
    }
}

public class NamedThreadFactory implements ThreadFactory {

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

    /**
     * 构造函数,接受将由此 ThreadFactory 创建的线程的前缀
     *
     * @param namePrefix
     *            线程名称的前缀
     */
    public NamedThreadFactory(String namePrefix) {
        this.namePrefix = namePrefix;
    }

    /**
     * 使用由此工厂指定的名称返回一个新线程 {@inheritDoc}
     */
    public Thread newThread(Runnable runnable) {
        return new Thread(runnable, namePrefix + " 线程-" + threadNumber.getAndIncrement());
    }
}
英文:

My code with @Guillaume logic. only thing i am thinking is AtomicInteger field should be class level rather then static as after each loop new pool is created as per my logic

public void run() {
log.info(name + &quot; Started&quot;);
ExecutorService executorService = null;
while (true) {
try {
List&lt;HashMap&lt;String, String&gt;&gt; rows = QueryFromDB;
int currentRecordSize = rows.size();                
if (currentRecordSize &gt; 0) {
NamedThreadFactory threadFactory = new NamedThreadFactory(name);
log.info(&quot; *** &quot; + name + &quot; Initializing Executor . Received &quot; + rows.size() + &quot; txns.&quot;);
if (currentRecordSize &lt; threadPoolSize) {
//executorService = Executors.newFixedThreadPool(currentRecordSize);
executorService = Executors.newFixedThreadPool(currentRecordSize, threadFactory);
} else {
//executorService = Executors.newFixedThreadPool(threadPoolSize);
executorService = Executors.newFixedThreadPool(threadPoolSize, threadFactory);
}
for (HashMap&lt;String, String&gt; 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(&quot;Exception in &quot; + name + &quot; Thread :&quot; + 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 + &quot; thread-&quot; + threadNumber.getAndIncrement());
}
}

huangapple
  • 本文由 发表于 2020年9月11日 23:41:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63850233.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定