Thread.enumerate方法的作用是将当前线程所对应的的线程组包含的所有线程放入一个数组
参见源码注释文章来源:https://www.toymoban.com/news/detail-684731.html
/**
* Copies into the specified array every active thread in the current
* thread's thread group and its subgroups. This method simply
* invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])}
* method of the current thread's thread group.
*
* <p> An application might use the {@linkplain #activeCount activeCount}
* method to get an estimate of how big the array should be, however
* <i>if the array is too short to hold all the threads, the extra threads
* are silently ignored.</i> If it is critical to obtain every active
* thread in the current thread's thread group and its subgroups, the
* invoker should verify that the returned int value is strictly less
* than the length of {@code tarray}.
*
* <p> Due to the inherent race condition in this method, it is recommended
* that the method only be used for debugging and monitoring purposes.
*
* @param tarray
* an array into which to put the list of threads
*
* @return the number of threads put into the array
*
* @throws SecurityException
* if {@link java.lang.ThreadGroup#checkAccess} determines that
* the current thread cannot access its thread group
*/
public static int enumerate(Thread tarray[]) {
return currentThread().getThreadGroup().enumerate(tarray);
}
eg:文章来源地址https://www.toymoban.com/news/detail-684731.html
public class TestLockSupport {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("执行前");
LockSupport.park();
System.out.println("执行后");
});
thread.start();
Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
Arrays.stream(threads).forEach(t -> System.out.println(t.getName()));
LockSupport.unpark(thread);
}
}
到了这里,关于Thread.enumerate方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!