线程类的 enumerate() 方法用于将每个活动线程的线程组及其子组复制到指定的数组中。此方法使用 tarray 参数调用 enumerate 方法。
此方法使用 activeCount 方法来估计数组应该有多大。如果数组的长度太短而无法容纳所有线程,则额外的线程将被静默忽略。
用法
public static int enumerate(Thread[] tarray)
参数
tarray:此方法是要复制到的 Thread 对象数组。
返回
此方法返回放入数组的线程数。
示例
public class JavaEnumerateExp extends Thread
{
JavaEnumerateExp(String threadname, ThreadGroup tg)
{
super(tg, threadname);
start();
}
public void run()
{
for (int i = 0; i < 5; i++)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ex) {
System.out.println("Exception encounterted");}
}
System.out.println(Thread.currentThread().getName() +" completed executing");
}
public static void main(String arg[]) throws InterruptedException,SecurityException
{
// 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
JavaEnumerateExp t1 = new JavaEnumerateExp("Thread-1", g1);
System.out.println("Starting of Thread-1");
// creating another thread
JavaEnumerateExp t2 = new JavaEnumerateExp("Thread-2", g1);
System.out.println("Starting of Thread-2");
// returns the number of threads put into the array
Thread[] group = new Thread[g1.activeCount()];
int count = g1.enumerate(group);
// prints active threads
for (int i = 0; i < count; i++)
{
System.out.println(group[i].getName() + " found");
}
}
}
输出:
Starting of Thread-1 Starting of Thread-2 Thread-1 found Thread-2 found Thread-1 completed executing Thread-2 completed executing
相关用法
- Java Thread toString()用法及代码示例
- Java Thread interrupted()用法及代码示例
- Java Thread setDefaultUncaughtExceptionHandler()用法及代码示例
- Java Thread suspend()用法及代码示例
- Java Thread destroy()用法及代码示例
- Java Thread holdLock()用法及代码示例
- Java Thread getContextClassLoader()用法及代码示例
- Java Thread setContextClassLoader()用法及代码示例
- Java Thread sleep()用法及代码示例
- Java Thread getThreadGroup()用法及代码示例
- Java Thread isInterrupted()用法及代码示例
- Java Thread notify()用法及代码示例
- Java Thread resume()用法及代码示例
- Java Thread activeCount()用法及代码示例
- Java Thread isDaemon()用法及代码示例
- Java Thread setDaemon()用法及代码示例
- Java Thread getId()用法及代码示例
- Java Thread setName()用法及代码示例
- Java Thread getDefaultUncaughtExceptionHandler()用法及代码示例
- Java Thread getState()用法及代码示例
注:本文由纯净天空筛选整理自 Java Thread enumerate() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。