2014-09-27 50 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()