1

我有一个ExecutorServiceandScheduledExecutorService我正在使用 customThreadFactory以便我可以根据 Thread 工厂的输入类型命名每个线程以runnable创建线程,但输入runnableThreadFactory类型是ThreadPoolExecutor$Worker. 以下是我的ThreadFactory实现。如何runnable从线程创建 ExecutorService中获取实际信息?ScheduledExecutorService

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

1 回答 1

1

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

于 2019-08-24T12:23:51.130 回答