Java Thread activeCount()方法

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

上一篇: Java Runtime類 下一篇:無