ThreadGroup.activeCount() 方法在 java 中不起作用
ThreadGroup.activeCount() method is not working in java
我正在学习多线程的概念,我试图找到数组中活动线程的数量,但是 ThreadGroup.activeCount( ) 只返回零值。
代码如下:
线程对象class :-
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");
}
}
主要class :-
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());
}
}
}
问题是在创建实例 th1
class 时,您将它们用作 Runnable
而不是 Thread
。并且那些包装器线程不与任何 ThreadGroup
相关联。声明变量如下。
Thread t1 = new th1("t-1", tg1);
t1.start();
我正在学习多线程的概念,我试图找到数组中活动线程的数量,但是 ThreadGroup.activeCount( ) 只返回零值。
代码如下:
线程对象class :-
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");
}
}
主要class :-
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());
}
}
}
问题是在创建实例 th1
class 时,您将它们用作 Runnable
而不是 Thread
。并且那些包装器线程不与任何 ThreadGroup
相关联。声明变量如下。
Thread t1 = new th1("t-1", tg1);
t1.start();