How many threads are there in one of the simplest Java programs?
The following program allows you to calculate the total number of threads for the current program.
import java.lang.management.ManagementFactory;import Java.lang.management.ThreadInfo; Public classmaintest { Public Static void Main(string[] args) {//calculation Method 1Threadgroup Threadgroup = Thread.CurrentThread().Getthreadgroup(); while(Threadgroup.getParent() !=NULL) {Threadgroup = Threadgroup.getParent(); }intTotalthread = Threadgroup.Activecount(); System. out.println("Total number of current program threads:"+ Totalthread); thread[] Lstthreads =NewThread[totalthread]; Threadgroup.Enumerate(lstthreads); for(inti =0; i < Totalthread; i++) {System. out.println("Thread Number:"+ Lstthreads[i].getId() +" = "+ Lstthreads[i].GetName()); }//calculation Method 2 //Get Java Thread Manager mxbean,dumpallthreads parameter: lockedmonitors parameter indicates whether to get synchronized monitor information, //lockedsynchronizers Indicates whether to get synchronized Synchronizerthreadinfo[] Threadinfos = managementfactory.Getthreadmxbean().dumpallthreads(false,false); for(Threadinfo Threadinfo:threadinfos) {System. out.println("["+ Threadinfo.GetThreadId() +"]"+ Threadinfo.Getthreadname()); } }}
There are two ways to calculate the number of threads:
1. Through the Java Thread Manager mxbean
2, directly through the thread group to get the total number of threads, pay attention to the need to get the total number of root thread groups, otherwise not accurate
Note that if Jetbrain ij comes to run this program, the result will be one more thread monitor ctrl-break. Running with debug does not occur.
Calculation Result:
5线程号:2 = Reference Handler线程号:3 = Finalizer线程号:4 = Signal Dispatcher线程号:5 = Attach Listener线程号:1 = main[5]Attach Listener[4]Signal Dispatcher[3]Finalizer[2]Reference Handler[1]main
Explained below,
[5] Attach Listener//Add Event
[4] Signal Dispatcher//distributing threads to JVM signals
[3] Finalizer//The thread that called the object Finalize method
[2] Reference Handler//Clear Reference Thread
[1]main//main Thread, program entry
Above
Resources:
Concurrent Programming Basics
Which threads are included in the simplest Java program?
Java viewing the number of running program threads
How many threads are there in one of the simplest Java programs?