英文:
Why does the Thread.activeCount() method returns 2?
问题
我目前正在学习关于Java线程。
public class Main {
public static void main(String[] args) {
System.out.println(Thread.activeCount());
}
}
有人可以告诉我为什么这个方法返回值为2吗?据我了解,目前只有"main"线程在运行。我知道Thread.activeCount()
"返回当前线程组及其子组中活动线程数的估计值",所以这个线程的子组中是否有另一个活动线程?
提前感谢您抽出时间来帮助我!
英文:
I am currently learning about Java threads.
public class Main {
public static void main(String[] args) {
System.out.println(Thread.activeCount());
}
}
Could anyone please tell me why does this method return the value 2? From what I understand, the only thread that is currently running is the "main" thread. I know that Thread.activeCount()
"Returns an estimate of the number of active threads in the current thread's thread group and its subgroups", so is there a subgroup of this thread that has another active thread?
Thank you in advance for taking the time to help me!
答案1
得分: 3
以下是已翻译的内容:
"Instead of guessing what threads these could be you can expand your code to write out the threads names:
public class ThreadCount {
public static void main(String[] args) {
System.out.println(Thread.activeCount() + " threads:");
Thread[] allThreads = new Thread[10];
Thread.enumerate(allThreads);
for (Thread t: allThreads) {
if (t != null) {
System.out.format("%d %s%n", t.getId(), t.getName());
}
}
}
}
On my windows machine this outputs:
2 threads:
1 main
14 Monitor Ctrl-Break
So the second thread is a JVM-created thread that seems to exist to monitor the Ctrl-Break key combination. Whether this thread is started or not may depend on your environment (running from console versus running a GUI application, running on Windows versus running on Linux, on Mac, on ....)"
英文:
Instead of guessing what threads these could be you can expand your code to write out the threads names:
public class ThreadCount {
public static void main(String[] args) {
System.out.println(Thread.activeCount() + " threads:");
Thread[] allThreads = new Thread[10];
Thread.enumerate(allThreads);
for (Thread t: allThreads) {
if (t != null) {
System.out.format("%d %s%n", t.getId(), t.getName());
}
}
}
}
On my windows machine this outputs:
> 2 threads:
> 1 main
> 14 Monitor Ctrl-Break
So the second thread is a JVM-created thread that seems to exist to monitor the Ctrl-Break key combination. Whether this thread is started or not may depend on your environment (running from console versus running a GUI application, running on Windows versus running on Linux, on Mac, on ....)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论