2014-09-27 48 views
0

问题当前线程数是当我跑代码在Java

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

是2,而不是1我认为这将是。 为什么有2个正在运行的线程?原因我认为有1个线程,所谓的主线程在方法主

+0

可能会有大量的后台线程。尝试'for(线程t:Thread.getAllStackTraces()。keySet())System.out.println(t);'看看你的情况。 – Holger 2014-09-27 18:50:33

+0

@Holger这肯定会给OP超过两个线程。 – 2014-09-27 19:43:32

+0

@Marko Topolnik:但你可以看到哪些线程属于同一个线程组。 – Holger 2014-09-27 19:54:07

回答

3

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

3

Thread#activeCount返回当前线程组中活动线程的数量。线程组main thread被称为main,在同一组中有另一个线程,称为Monitor Ctrl-Break,。这就是为什么Thread.activeCount在你的情况下返回2。请注意,此行为是特定于平台的。 您可以使用

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

以获取实时线程和iterater在他们看到关于他们的详细信息,这样

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

这可能是特定于平台的,在OS X上我得到一个单一的线程数。但无论如何,这是唯一的答案,即使*试图解决实际问题+1。 – 2014-09-27 19:35:14

+0

@MarkoTopolnik tx,的确是平台特定的。我在linux上运行代码。答案已更新。 – sol4me 2014-09-27 20:16:44

0

如果你真的想知道发生了什么事情的所有线程,

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 
    } 
0
Thread.activeCount(); 

返回当前线程中活动线程数的估计值线程组及其子组。递归地遍历当前线程的线程组中的所有子组。

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.

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