Java Thread activeCount()方法

2019-10-16 22:24:41

Thread類的activeCount()方法用於返回當前執行緒的執行緒組中活動執行緒的數量。返回的值只是一個估計值,因為當此方法遍歷內部資料結構時,執行緒數可能會動態更改。

語法

public static int activeCount()

返回

它返回當前執行緒的執行緒組中活動執行緒的數量。

範例

public class JavaActiveCountExp extends Thread   
{  
    JavaActiveCountExp(String threadname, ThreadGroup tg)  
    {  
        super(tg, threadname);  
        start();  
    }  
    public void run()  
    {  
       System.out.println("running thread name is: "+Thread.currentThread().getName());    
    }  
    public static void main(String arg[])  
    {  
        // creating the thread group  
        ThreadGroup g1 = new ThreadGroup("parent thread group");  

        // creating a thread   
        JavaActiveCountExp t1 = new JavaActiveCountExp("Thread-1", g1);  
        // creating another thread   
        JavaActiveCountExp t2 = new JavaActiveCountExp("Thread-2", g1);  

        // checking the number of active thread  
        System.out.println("number of active thread: "+ g1.activeCount());  
    }  
}

執行上面範例程式碼,得到以下結果:

number of active thread: 2
running thread name is: Thread-1
running thread name is: Thread-2