ThreadGroup.activeCount() 方法在 java 中不起作用

我正在学习多线程的概念,我试图查找数组中的活动线程数,但ThreadGroup.activeCount()方法仅返回零值。


这是代码:


线程对象类:-


class th1 extends Thread

{

    public th1(String threadName, ThreadGroup tg1)

    {

        super(tg1, threadName);

    }


    @Override

    public void run() 

    {

        try {

            Thread.sleep(5000);

        } 

        catch (InterruptedException e) 

        {

            e.printStackTrace();

        }


        System.out.println(Thread.currentThread().getName() + " is running");

    }

}

主要课程:-


public class enumerate_demo 

{

    public static void main(String[] args) 

    {

        ThreadGroup tg1 = new ThreadGroup("group 1");


        Thread t1 = new Thread(new th1("t-1", tg1));

        t1.start();


        Thread t2 = new Thread(new th1("t-2", tg1));

        t2.start();


        Thread t3 = new Thread(new th1("t-3", tg1));

        t3.start();


        System.out.println("Number of active count :- " + tg1.activeCount());


        Thread[] group = new Thread[tg1.activeCount()];


        int count = tg1.enumerate(group);


        for (int i = 0; i < count; i++)

        {

            System.out.println("Thread " + group[i].getName());

        }

    }

}


GCT1015
浏览 77回答 1
1回答

慕斯王

问题是,在创建实例th1类时,您将它们用作Runnable与Thread.&nbsp;这些包装线程不与任何ThreadGroup.&nbsp;声明变量如下。&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Thread&nbsp;t1&nbsp;=&nbsp;new&nbsp;th1("t-1",&nbsp;tg1); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t1.start();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java