问题描述
假设我有一个使用 Executor
框架的应用程序
Let's say I have an application that utilizes the Executor
framework as such
Executors.newSingleThreadExecutor().submit(new Runnable(){
@Override
public void run(){
// do stuff
}
}
当我在调试器中运行此应用程序时,将使用以下(默认)名称创建一个线程: 线程[pool-1-thread-1]
。正如您所看到的,这不是非常有用,据我所知, Executor
框架没有提供一种简单的方法来命名创建的线程或线程池。
When I run this application in the debugger, a thread is created with the following (default) name: Thread[pool-1-thread-1]
. As you can see, this isn't terribly useful and as far as I can tell, the Executor
framework does not provide an easy way to name the created threads or thread-pools.
那么,如何提供名称?线程/线程池?例如,线程[FooPool-FooThread]
。
So, how does one go about providing names for the threads/thread-pools? For instance, Thread[FooPool-FooThread]
.
推荐答案
您可以提供到。工厂将负责创建线程,并且可以命名它们。
You could supply a ThreadFactory
to newSingleThreadScheduledExecutor(ThreadFactory threadFactory)
. The factory will be responsibe for creating threads, and will be able to name them.
引用:
使用 ThreadFactory
创建新线程。如果没有另外指定,则使用 Executors.defaultThreadFactory()
,它创建的线程都在同一个 ThreadGroup
中并具有相同的 NORM_PRIORITY
优先级和非守护程序状态。通过提供不同的 ThreadFactory
,您可以更改线程的名称,线程组,优先级,守护程序状态等。如果 ThreadFactory
通过从 newThread
返回null询问时无法创建线程,执行程序将继续,但可能无法执行任何任务
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
这篇关于命名ExecutorService的线程和线程池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!