java 如何更改 ExecutorService 中的线程名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6126124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change the name of threads in an ExecutorService?
提问by Renato Dinhani
I'm using an ExecutorService to execute some Callables, but the name of the threads are like fixed-pool-1-thread-1.
我正在使用 ExecutorService 来执行一些 Callables,但线程的名称类似于 fixed-pool-1-thread-1。
How I change the name of the threads? If it's not possible, there another way to execute Callables that I can set the name of threadS?
我如何更改线程的名称?如果不可能,还有另一种执行可调用的方法,我可以设置 threadS 的名称吗?
回答by Edward Dale
You'll have to use an ExecutorService
implementation that allows you to set the ThreadFactory
1used to create threads, for example, ThreadPoolExecutor
. Pass an instance that creates threads with the proper names.
您必须使用ExecutorService
允许您设置用于创建线程的ThreadFactory
1的实现,例如,ThreadPoolExecutor
. 传递一个创建具有正确名称的线程的实例。
There's also a handy class in commons-lang that allows to specify thread names with a pattern: BasicThreadFactory
. This keeps you from having to create a ThreadFactory
subclass just to provide the naming behavior.
还有在公共浪一个方便的类,允许用一个模式指定线程名称:BasicThreadFactory
。这使您不必ThreadFactory
为了提供命名行为而创建子类。
回答by pathikrit
Guava almost always has what you need. ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("my-sad-thread-%d").build()
and pass it off to your ExecutorService
.
Guava 几乎总能满足您的需求。ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("my-sad-thread-%d").build()
并将其传递给您的ExecutorService
.
回答by Kirk
A quick and dirty way;
一种快速而肮脏的方式;
public void run() {
Thread.currentThread().setName(aName);
doStuff();
}