问题描述
我正在使用ExecutorService线程池执行可调用对象。我想给这个帖子命名。
I am executing a Callable Object using ExecutorService thread pool. I want to give a name to this thread.
更具体地说,在旧版本中我做了这个 -
To be more specific, in older version I did this -
Thread thread = new Thread(runnable Task);
thread.setName("My Thread Name");
我在log4j日志记录中使用线程名称,这在故障排除时有很大帮助。现在我将我的代码从Java 1.4迁移到Java 1.6。我写了这个(如下所示) - 但我不知道如何给这个帖子命名。
I use thread name in log4j logging, this helps a lot while troubleshooting. Now I am migrating my code from Java 1.4 to Java 1.6. I have written this(Given below)- but I dont know how to give name to this thread.
private final ExecutorService executorPool = Executors.newCachedThreadPool();
Future<String> result = executorPool.submit(callable Task);
请给我一些想法给这个帖子命名?
Please give me some idea to give name to this thread?
推荐答案
您可以使用重载方法:
java.util.concurrent.Executors.newCachedThreadPool(ThreadFactory)
允许你传递
java.util.concurrent.ThreadFactory
应允许您通过 java.util.concurrent.ThreadFactory.newThread(Runnable)设置线程的名称
:
查看 java.util.concurrent.Executors.DefaultThreadFactory
以获取默认实现。
附录
因为我看到这个帖子仍然被访问过,所以Guava(如果有的话)提供了,充分利用了内部匿名类,甚至允许为线程自定义参数化名称。
Since I see that this thread is still visited, Guava (if you have it available) provides a ThreadFactoryBuilder that leverages the need of having an inner anonymous class and even allows for customizing parametrized names for your threads.
这篇关于如何为可调用线程命名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!