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

ScheduledExecutorServiceAcquirerTransaction实现IssuerTransaction

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

最佳答案

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

09-30 09:58