Java中如何给线程池中的线程命名
我有一个使用 Executor
框架的 Java 应用程序,并且我的代码如下所示 protected ScheduledExecutorService ScheduledExecutorService = new ScheduledThreadPoolExecutor(5)
我的理解是,JVM 在内部会创建一个包含 5 个线程的池。现在,当我在探查器中检查执行情况时,我会得到类似 thread-pool2,thread-pool3
等信息。
这些线程池有些是服务器创建的,有些是我创建的
,我需要一种方法来区分哪些是我创建的,哪些是服务器创建的。
我想,如果我可以命名线程池,它应该可以解决问题,但是没有看到任何 API 可以让我做同样的事情。
提前致谢。
I have a Java application that uses the Executor
framework and I have code that looks like thisprotected ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(5)
My understanding is that internally the JVM would create a pool of 5 threads. Now when I check the execution in a profiler, I get something like thread-pool2,thread-pool3
and so on.
Some of these thread pools are created by the server and some are created by me
, I need a way to differentiate which were created by me and which were created by the server.
I am thinking that if I can name the thread pools it should do the trick, however do not see any API which would allow me to do the same.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将自己的 ThreadFactory 传递给ScheduledThreadPoolExecutor。您的 ThreadFactory 将创建线程并可以为其指定任何您想要的名称。您的 ThreadFactory 还可以重用 执行器。 defaultThreadFactory(),并且仅在返回线程之前更改名称。
You can pass your own ThreadFactory to ScheduledThreadPoolExecutor. Your ThreadFactory will create thread and can give it any name you want. Your ThreadFactory can also reuse Executors.defaultThreadFactory(), and only change the name before returning the thread.
来自 ThreadPoolExecutor 文档:
From the ThreadPoolExecutor documentation:
使用您自己的自定义线程工厂。实现 ThreadFactoryBuilder 来创建自定义线程工厂,它允许您执行以下操作:
您可以在您可以使用以下帖子。
http://wilddiary.com/understanding-java-threadfactory-creating-自定义线程工厂/
Use your own custom thread factory. Implement a ThreadFactoryBuilder to create you custom thread factories that allows you to do the following:
You have a sample ThreadFactoryBuilder implementation in the following post which you can use.
http://wilddiary.com/understanding-java-threadfactory-creating-custom-thread-factories/