當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Thread enumerate()用法及代碼示例


線程類的 enumerate() 方法用於將每個活動線程的線程組及其子組複製到指定的數組中。此方法使用 tarray 參數調用 enumerate 方法。

此方法使用 activeCount 方法來估計數組應該有多大。如果數組的長度太短而無法容納所有線程,則額外的線程將被靜默忽略。

用法

public static int enumerate(Thread[] tarray)

參數

tarray:此方法是要複製到的 Thread 對象數組。

返回

此方法返回放入數組的線程數。

示例

public class JavaEnumerateExp extends Thread 
{
    JavaEnumerateExp(String threadname, ThreadGroup tg)
    {
        super(tg, threadname);
        start();
    }
    public void run()
    {
        for (int i = 0; i < 5; i++) 
        {
            try
            {
                Thread.sleep(10);
            }	
            catch (InterruptedException ex) {
                System.out.println("Exception encounterted");}
        }
        System.out.println(Thread.currentThread().getName() +" completed executing");
    }
    public static void main(String arg[]) throws InterruptedException,SecurityException
    {
        // creating the ThreadGroup
        ThreadGroup g1 = new ThreadGroup("Parent thread");
        // creating a child ThreadGroup for parent ThreadGroup
        ThreadGroup g2 = new ThreadGroup(g1, "child thread");
 
        // creating a thread 
        JavaEnumerateExp t1 = new JavaEnumerateExp("Thread-1", g1);
        System.out.println("Starting of Thread-1");
        // creating another thread 
        JavaEnumerateExp t2 = new JavaEnumerateExp("Thread-2", g1);
        System.out.println("Starting of Thread-2");
 
        // returns the number of threads put into the array
        Thread[] group = new Thread[g1.activeCount()];
        int count = g1.enumerate(group);
        
        // prints active threads
        for (int i = 0; i < count; i++) 
        {
            System.out.println(group[i].getName() + " found");
        }
    }
}

輸出:

Starting of Thread-1
Starting of Thread-2
Thread-1 found
Thread-2 found
Thread-1 completed executing
Thread-2 completed executing






相關用法


注:本文由純淨天空篩選整理自 Java Thread enumerate() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。