ExecutorService 的命名线程和线程池 [英] Naming threads and thread-pools of ExecutorService

查看:98
本文介绍了ExecutorService 的命名线程和线程池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个使用 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
    }
}

当我在调试器中运行此应用程序时,会创建一个具有以下(默认)名称的线程:Thread[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.

那么,如何为线程/线程池提供名称?例如,Thread[FooPool-FooThread].

So, how does one go about providing names for the threads/thread-pools? For instance, Thread[FooPool-FooThread].

推荐答案

你可以提供一个 ThreadFactorynewSingleThreadScheduledExecutor(ThreadFactory threadFactory).工厂将负责创建线程,并将能够命名它们.

You could supply a ThreadFactory to newSingleThreadScheduledExecutor(ThreadFactory threadFactory). The factory will be responsibe for creating threads, and will be able to name them.

引用Javadoc:

创建新线程

使用 ThreadFactory 创建新线程.如果没有另外指定,则使用 Executors.defaultThreadFactory(),它创建的线程都在相同的 ThreadGroup 中并且具有相同的 NORM_PRIORITY优先级和非守护进程状态.通过提供不同的 ThreadFactory,您可以更改线程的名称、线程组、优先级、守护进程状态等.如果 ThreadFactory 在通过返回 null 询问时未能创建线程从 newThread 开始,执行程序将继续执行,但可能无法执行任何任务

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 的命名线程和线程池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆