一個最簡單的Java程式有多少線程?

來源:互聯網
上載者:User

標籤:計算   線程   sig   pre   main   blog   tac   inf   參數   

一個最簡單的Java程式有多少線程?
通過下面程式可以計算出當前程式的線程總數。

import java.lang.management.ManagementFactory;import java.lang.management.ThreadInfo;public class MainTest {    public static void main(String[] args) {        // 計算方法1        ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();        while (threadGroup.getParent() != null) {            threadGroup = threadGroup.getParent();        }        int totalThread = threadGroup.activeCount();        System.out.println("當前程式線程總數: " + totalThread);        Thread[] lstThreads = new Thread[totalThread];        threadGroup.enumerate(lstThreads);        for (int i = 0; i < totalThread; i++) {            System.out.println("線程號:" + lstThreads[i].getId() + " = " + lstThreads[i].getName());        }        // 計算方法2        // 擷取java線程管理器MXBean,dumpAllThreads參數:lockedMonitors參數表示是否擷取同步的monitor資訊,                //lockedSynchronizers表示是否擷取同步的synchronizer        ThreadInfo[] threadInfos = ManagementFactory.getThreadMXBean().dumpAllThreads(false, false);        for (ThreadInfo threadInfo : threadInfos) {            System.out.println("[" + threadInfo.getThreadId() + "]" + threadInfo.getThreadName());        }    }}

上面有兩種計算線程數的方式:

1、通過java線程管理器MXBean
2、直接通過線程組擷取線程總數,要注意需要擷取根線程組的總數,否則不準確

注意,如果JetBrain IJ來Run這個程式,結果會多一個線程Monitor Ctrl-Break。使用Debug運行不會出現。

計算結果:

當前程式線程總數: 5線程號:2 = Reference Handler線程號:3 = Finalizer線程號:4 = Signal Dispatcher線程號:5 = Attach Listener線程號:1 = main[5]Attach Listener[4]Signal Dispatcher[3]Finalizer[2]Reference Handler[1]main

解釋如下,

[5]Attach Listener //添加事件
[4]Signal Dispatcher // 分發處理給JVM訊號的線程
[3]Finalizer //調用對象finalize方法的線程
[2]Reference Handler //清除reference線程
[1]main //main線程,程式入口

上面

參考資料:
並發編程基礎
最簡單Java程式包含有哪些線程?
Java 查看運行程式線程數

一個最簡單的Java程式有多少線程?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.