How to change the name of threads in ExecutorService?

I use ExecutorService to execute some Callables, but the thread name is similar to fixed-pool-1-thread-1.

How do I change the name of threads? If this is not possible, is there another way to execute Callables so that I can set the threadS name?

+7
source share
3 answers

You will need to use the ExecutorService implementation, which allows you to set ThreadFactory 1 , used to create threads, for example, ThreadPoolExecutor . Pass the instance that creates the streams with names.

There is also a handy class in commons-lang that allows you to specify thread names with a pattern: BasicThreadFactory . This ThreadFactory you from subclassing ThreadFactory to provide naming behavior.

+11
source

Guava almost always has what you need . ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("my-sad-thread-%d").build() and pass it to the ExecutorService .

+5
source

Quick and dirty way;

 public void run() { Thread.currentThread().setName(aName); doStuff(); } 
+3
source

All Articles