ThreadGroup类的enumerate()方法

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

语法

public int enumerate(Thread[] tarray)

 

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

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 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");
    }
}

Java

执行上面示例代码,得到以下结果:

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

 

原文链接:https://www.yiibai.com/java_multithreading/java-threadgroup-enumerate-method.html
 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

那些年的代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值