假设我有一个利用Executor框架的应用程序

Executors.newSingleThreadExecutor().submit(new Runnable(){
    @Override
    public void run(){
        // do stuff
    }
}

当我在调试器中运行此应用程序时,将创建一个具有以下(默认)名称的线程:thread [pool-1-thread-1]。正如您所看到的,这并不是非常有用,而且据我所知,Executor框架并没有提供一种简单的方法来命名创建的线程或线程池。

那么,如何为线程/线程池提供名称呢?例如,Thread[fopool - foothread]。


当前回答

private class TaskThreadFactory implements ThreadFactory
{

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(r, "TASK_EXECUTION_THREAD");

        return t;
    }

}

将ThreadFactory传递给一个executorservice,就可以开始了

其他回答

Executors.newSingleThreadExecutor(r -> new Thread(r, "someName")).submit(getJob());

Runnable getJob() {
        return () -> {
            // your job
        };
}

您可以尝试提供自己的线程工厂,它将创建具有适当名称的线程。这里有一个例子:

class YourThreadFactory implements ThreadFactory {
   public Thread newThread(Runnable r) {
     return new Thread(r, "Your name");
   }
 }

Executors.newSingleThreadExecutor(new YourThreadFactory()).submit(someRunnable);

或者用Kotlin

Executors.newSingleThreadExecutor { r -> Thread(r, "Your name") }

你可以提供一个ThreadFactory给newSingleThreadScheduledExecutor(ThreadFactory)。工厂将负责创建线程,并能够为它们命名。

引用Javadoc的话:

Creating new threads New threads are created using a ThreadFactory. If not otherwise specified, a Executors.defaultThreadFactory() is used, that creates threads to all be in the same ThreadGroup and with the same NORM_PRIORITY priority and non-daemon status. By supplying a different ThreadFactory, you can alter the thread's name, thread group, priority, daemon status, etc. If a ThreadFactory fails to create a thread when asked by returning null from newThread, the executor will continue, but might not be able to execute any tasks

如果使用Spring,可以为CustomizableThreadFactory设置线程名前缀。

例子:

ExecutorService alphaExecutor =
    Executors.newFixedThreadPool(10, new CustomizableThreadFactory("alpha-"));

或者,您可以使用ThreadPoolExecutorFactoryBean将ExecutorService创建为Spring bean——然后所有线程都将以beanName-前缀命名。

@Bean
public ThreadPoolExecutorFactoryBean myExecutor() {
    ThreadPoolExecutorFactoryBean executorFactoryBean = new ThreadPoolExecutorFactoryBean();
    // configuration of your choice
    return executorFactoryBean;
}

在上面的例子中,线程将以myExecutor-前缀命名。您可以显式地将前缀设置为不同的值(例如。通过在工厂bean上设置executorFactoryBean.setThreadNamePrefix("myPool-")来实现。

根据上面的一些注释,不同之处在于我只使用了lambda

Executors.newFixedThreadPool(10, r -> new Thread(r, "my-threads-%d"))