Java ThreadGroup activeCount()方法

2019-10-16 22:23:52

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

語法

public static int activeCount()

返回值

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

範例

package com.yiibai.threadgroup;

class NewThread extends Thread {
    NewThread(String threadname, ThreadGroup tg) {
        super(tg, threadname);
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException ex) {
                System.out.println(Thread.currentThread().getName() + " interrupted");
            }
        }
        System.out.println(Thread.currentThread().getName() + " completed executing");
    }
}

public class ThreadGroupActiveCountExp {
    public static void main(String arg[]) {
        // creating the thread group
        ThreadGroup tg1 = new ThreadGroup("parent thread group");

        // creating the threads
        NewThread t1 = new NewThread("Thread-1", tg1);
        NewThread t2 = new NewThread("Thread-2", tg1);
        NewThread t3 = new NewThread("Thread-3", tg1);

        // this will call the run() method
        t1.start();
        t2.start();
        t3.start();

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

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

Number of active thread: 3
Thread-1 completed executing
Thread-2 completed executing
Thread-3 completed executing