简体   繁体   English

Java中的守护程序线程计数

[英]Daemon Thread Count in Java

Is there a way to get the count of active daemon threads running in java ? 有没有一种方法来获取在Java中运行的活动守护线程的数量?

I used, Thread.getAllStackTraces().keySet().size() but it did not give the correct result. 我使用了Thread.getAllStackTraces().keySet().size()但是它没有给出正确的结果。

This question has reference to the count of daemon threads but it did not have any code for the same. 这个问题参考了守护程序线程的数量,但是没有相同的代码。

Could some one please help me on this or any reference on this would also be of great help. 有人可以帮我这个忙吗,或者对此有任何参考也会很有帮助。

Thanks in advance ! 提前致谢 !

You can do it via Thread.getAllStackTraces : 您可以通过Thread.getAllStackTraces做到这Thread.getAllStackTraces

public static void main(String[] args) {
   Set<Thread> threads =  Thread.getAllStackTraces().keySet();
   threads.forEach(t -> {
   System.out.println(t.getName()+ " : " + t.isDaemon()); // count if isDaemon is true
   });

}

O/P : O / P:

Signal Dispatcher : true 
main : false 
Finalizer : true 
Reference Handler : true

I think you can use ThreadMXBean#getDaemonThreadCount() API which returns the current number of live daemon threads. 我认为您可以使用ThreadMXBean#getDaemonThreadCount() API来返回当前活动守护线程的数量。

ManagementFactory.getThreadMXBean().getDaemonThreadCount();

For more info please follow the link . 欲了解更多信息,请点击链接

You can write your custom implementation for this like 您可以为此编写自定义实现,例如

int daemonThreadCount = 0;
for (Thread thread : Thread.getAllStackTraces().keySet()) {
    if (thread.isDaemon()) {
        daemonThreadCount++;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM