有没有一种方法可以使用代码打印出所有线程及其 id、状态呢?
例如,我有5个线程,我想枚举它们所有。
例如,我有5个线程,我想枚举它们所有。
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for (Thread thread: threadSet) {
System.out.println(thread.getId());
}
在使用 Thread.getAllStackTraces() 方法之前,请确保您已经阅读并理解了该方法。
注意:请勿删除 HTML 标签。使用 Thread.currentThread().getId();
public int myThreadId = 0;
public void run () {
System.out.println("Thread Name: " + Thread.currentThread().getName(); // Printing the thread name
myThreadId = Thread.currentThread().getId(); // Assigning the thread ID to a public variable
}
阅读更多:如何获取Java线程的引用 | eHow.com http://www.ehow.com/how_6879305_reference-java-thread.html#ixzz2FfEUe3cF
另外
像这样获取根ThreadGroup的句柄:
ThreadGroup rootGroup = Thread.currentThread( ).getThreadGroup( );
ThreadGroup parentGroup;
while ( ( parentGroup = rootGroup.getParent() ) != null ) {
rootGroup = parentGroup;
}
Thread[] threads = new Thread[ rootGroup.activeCount() ];
while ( rootGroup.enumerate( threads, true ) == threads.length ) {
threads = new Thread[ threads.length * 2 ];
}