当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ThreadGroup enumerate()用法及代码示例


ThreadGroup 类的 enumerate() 方法用于将每个活动线程的线程组及其子组复制到指定的数组中。此方法使用 tarray 参数调用 enumerate 方法。

用法

public int enumerate(Thread[] tarray)

参数

tarray:它是要复制到的 Thread 对象数组。

返回

此方法返回放入数组的线程数。

示例

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 ThreadGroupEnumerateExp
{
    public static void main(String arg[]) 
    {
        // 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 
        NewThread t1 = new NewThread("Thread-1", g1);
        System.out.println("Starting of Thread-1");
        t1.start();
        // creating another thread 
        NewThread t2 = new NewThread("Thread-2", g1);
        System.out.println("Starting of Thread-2");
        t2.start();
 
        // returns the number of threads put into the array
        Thread[] tarray = new Thread[g1.activeCount()];
        int count = g1.enumerate(tarray);
        
        // prints active threads
        for (int i = 0; i < count; i++) 
            System.out.println(tarray[i].getName() + " found");
    }
}

输出:

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






相关用法


注:本文由纯净天空筛选整理自 Java ThreadGroup enumerate() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。