首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ThreadGroup.activeCount()方法不适用于java

ThreadGroup.activeCount()方法不适用于java
EN

Stack Overflow用户
提问于 2019-11-04 03:29:54
回答 1查看 352关注 0票数 0

我正在学习多线程的概念,在这个概念中,我试图在数组中找到活动线程的数量,但是ThreadGroup.activeCount()的方法只是返回它的零值。

以下是代码:

线程对象类 :-

代码语言:javascript
复制
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");
    }
}

主类 :-

代码语言:javascript
复制
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());
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-04 04:04:52

问题是,在创建实例th1类时,您使用它们作为Runnable而不是Thread。而这些包装线程与任何ThreadGroup都没有关联。按以下方式声明变量。

代码语言:javascript
复制
        Thread t1 = new th1("t-1", tg1);
        t1.start(); 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58686847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档