[英]Implement custom naming for ExecutorService ScheduledExecutorService based on instance type of runnable input to ThreadFactory
I have a ExecutorService
and ScheduledExecutorService
for which I am using custom ThreadFactory
so that I can name every thread as per type of runnable
input to Thread factory for thread creation, but the input runnable
to ThreadFactory
is of type ThreadPoolExecutor$Worker
.我有一个ExecutorService
和ScheduledExecutorService
,我使用自定义ThreadFactory
以便我可以根据线程工厂的runnable
输入类型命名每个线程以创建线程,但runnable
到ThreadFactory
的输入类型为ThreadPoolExecutor$Worker
。 Following is my ThreadFactory
implemntation.以下是我的ThreadFactory
实现。 How can I get actual runnable
from ExecutorService
and ScheduledExecutorService
for thread creation?如何从ExecutorService
和ScheduledExecutorService
获得实际runnable
的线程创建?
AcquirerTransaction
& IssuerTransaction
implements Runnable
. AcquirerTransaction
和IssuerTransaction
实现了Runnable
。
private final ThreadFactory threadFactory = new CustomThreadFactory(config.bankId, config);
private final ScheduledThreadPoolExecutor schedular = new ScheduledThreadPoolExecutor(5, threadFactory);
private final ThreadPoolExecutor executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory);
public final class CustomThreadFactory implements ThreadFactory {
private final String prefix;
private final CoreConfig config;
private AtomicInteger counter = new AtomicInteger(0);
public CustomThreadFactory(final String prefix, final CoreConfig config) {
this.prefix = prefix;
this.config = config;
}
//@formatter:off
@Override
public final Thread newThread(Runnable runnable) {
if(runnable instanceof Scheduled) return new Thread(runnable, getName(prefix, "sch", counter.getAndIncrement()));
else if (runnable instanceof AcquirerTransaction || runnable instanceof NoLogAcquirerTransaction) return new Thread(runnable, getName(prefix, "acq", counter.getAndIncrement()));
else if (runnable instanceof IssuerTransaction || runnable instanceof NoLogIssuerTransaction) return new Thread(runnable, getName(prefix, "iss", counter.getAndIncrement()));
else return new Thread(runnable, getName(prefix, "gen", counter.getAndIncrement()));
}
private static final String getName(final String prefix, final String type, final int count) {
return prefix + "-" + type + "-" + count;
}
public final String getPrefix() {
return prefix;
}
}
You could set the current thread's name at start of runnable execution and clear it at end.您可以在可运行执行开始时设置当前线程的名称,并在结束时清除它。 Use the static curentThread method to obtain the Thead ans then the setName method.使用静态 curentThread 方法获取 Thead 和 setName 方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.