gpt4 book ai didi

java - 根据 ThreadFactory 的可运行输入的实例类型为 ExecutorService ScheduledExecutorService 实现自定义命名

转载 作者:行者123 更新时间:2023-11-30 05:30:38 25 4
gpt4 key购买 nike

我有一个 ExecutorServiceScheduledExecutorService,我正在使用自定义 ThreadFactory,以便我可以根据 的类型命名每个线程>runnable 输入到 Thread 工厂用于创建线程,但输入到 ThreadFactoryrunnable 类型为 ThreadPoolExecutor$Worker。以下是我的 ThreadFactory 实现。如何从 ExecutorServiceScheduledExecutorService 获取实际的 runnable 来创建线程?

AcquirerTransactionIssuerTransaction 实现 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;
}
}

最佳答案

您可以在可运行执行开始时设置当前线程的名称,并在结束时清除它。使用静态的 currentThread 方法获取 Thead,然后使用 setName 方法。

关于java - 根据 ThreadFactory 的可运行输入的实例类型为 ExecutorService ScheduledExecutorService 实现自定义命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57636151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com