如何查看Java进程中的线程数?
Answers:
java.lang.Thread.activeCount()
它将返回当前线程的线程组中活动线程的数量。
docs:http : //docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#activeCount()
ManagementFactory.getThreadMXBean().getThreadCount()
不会像线程组那样限制自己Thread.activeCount()
。
top
。虽然在调试窗口中,但我只看到2个线程正在运行,而不是5个。:/
import java.lang.management.ManagementFactory;
docs.oracle.com/javase/8/docs/api/java/lang/management/…getPeakThreadCount()
自己开始做之前, 请参见和其他方法:)
通用解决方案不需要jconsole之类的GUI(不适用于远程终端),ps适用于非Java进程,不需要安装JVM。
ps -o nlwp <pid>
我编写了一个程序来迭代所有Threads
创建和打印getState()
的程序Thread
import java.util.Set;
public class ThreadStatus {
public static void main(String args[]) throws Exception{
for ( int i=0; i< 5; i++){
Thread t = new Thread(new MyThread());
t.setName("MyThread:"+i);
t.start();
}
int threadCount = 0;
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for ( Thread t : threadSet){
if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup()){
System.out.println("Thread :"+t+":"+"state:"+t.getState());
++threadCount;
}
}
System.out.println("Thread count started by Main thread:"+threadCount);
}
}
class MyThread implements Runnable{
public void run(){
try{
Thread.sleep(2000);
}catch(Exception err){
err.printStackTrace();
}
}
}
输出:
java ThreadStatus
Thread :Thread[MyThread:0,5,main]:state:TIMED_WAITING
Thread :Thread[main,5,main]:state:RUNNABLE
Thread :Thread[MyThread:1,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:4,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:2,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:3,5,main]:state:TIMED_WAITING
Thread count started by Main thread:6
如果您删除以下情况
if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup())
您还将在输出中得到以下线程,这些线程已由系统启动。
Reference Handler, Signal Dispatcher,Attach Listener and Finalizer
。
public class MainClass {
public static void main(String args[]) {
Thread t = Thread.currentThread();
t.setName("My Thread");
t.setPriority(1);
System.out.println("current thread: " + t);
int active = Thread.activeCount();
System.out.println("currently active threads: " + active);
Thread all[] = new Thread[active];
Thread.enumerate(all);
for (int i = 0; i < active; i++) {
System.out.println(i + ": " + all[i]);
}
}
}