简体   繁体   English

Java中的当前线程数

[英]Number of current threads in java

The problem is when I ran code 问题是当我运行代码时

public static void main(String... args) throws InterruptedException{
        System.out.println(Thread.activeCount());
    }

it was 2 instead of 1 I thought it would be. 我以为是2,而不是1。 Why there 2 running threads? 为什么会有2个正在运行的线程? Cause I thought there is 1 thread, so called main thread in method main 原因我认为有1个线程,所以在方法main中称为主线程

JVM本身可以有任意数量的工作线程,例如GC线程。

Thread#activeCount return number of active threads in current thread group. Thread#activeCount返回当前线程组中活动线程的数量。 The thread group of main thread is called main and in the same group there is another thread called Monitor Ctrl-Break, . main thread的线程组称为main ,在同一线程组中还有另一个线程,称为Monitor Ctrl-Break, That's why Thread.activeCount returns 2 in your case. 这就是Thread.activeCount在您的情况下返回2的原因。 Note that this behavior is platform specific. 请注意,此行为是特定于平台的。 You can use 您可以使用

Set<Thread> set = Thread.getAllStackTraces().keySet();

to get live threads and iterater over them to see details about them, like this 获取活动线程并遍历它们以查看有关它们的详细信息,例如

for (Thread thread : set) {
    System.out.println(thread.getName() + ", "+ thread.getThreadGroup());
}

If you really want to know what's going on with all the threads, 如果您真的想知道所有线程的状态,

  public static void logThreadDumps() {
    StringBuilder sb = new StringBuilder(32768);
    sb.append("============ THREAD DUMP ============\n");
    ThreadInfo[] threads = ManagementFactory.getThreadMXBean().dumpAllThreads(true, true);
    for (ThreadInfo info : threads) {
      sb.append(info);
    }
    System.out.println(sb.toString());  // or log it
  }
Thread.activeCount(); 

Returns an estimate of the number of active threads in the current thread's thread group and its subgroups. 返回当前线程的线程组及其子组中活动线程的数量的估计值。 Recursively iterates over all subgroups in the current thread's thread group. 递归地迭代当前线程的线程组中的所有子组。

The value returned is only an estimate because the number of threads may change dynamically while this method traverses internal data structures, and might be affected by the presence of certain system threads.

Visit http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#activeCount() 访问http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#activeCount()

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

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