Why the first Thread.activeCount() return 1 but another return 2 in my code?

后端 未结 3 1539
故里飘歌
故里飘歌 2021-01-28 06:34

Here is my application:

public class NamedThread extends Thread {
    /* This will store name of the thread */

    String name;

    @Override
    public void r         


        
相关标签:
3条回答
  • 2021-01-28 07:16

    If we print all the threads then we can observe that default thread group is System and inside the system, there are different threads and groups like :

    Group[system:class java.lang.ThreadGroup]
     Reference
      Finalizer
      Signal Dispatcher
      Group[main:class java.lang.ThreadGroup]
         main
         Monitor
      Group[InnocuousThreadGroup:class java.lang.ThreadGroup]
        Common-Cleaner
    

    In java code default thread group is main. When we print active thread count then it will give an answer as 2 because the main thread group has two threads main and monitor.

    0 讨论(0)
  • 2021-01-28 07:23
    public static void main(String[] args) {
        System.out.println(Thread.activeCount());
    
        //doSomething()
    }
    

    The code above output 2

    GC occupies a thread, so you get 2, instead of 1

    This function is designed for debugging

    If you run on debug mode, you would get 1

    0 讨论(0)
  • 2021-01-28 07:26

    InteliJ generates another thread that is called Monitor Ctrl-Break thread.

    The following code (took it from https://www.tutorialspoint.com/java/lang/thread_activecount.htm):

    public static void main(String[] args) {
    
                Thread t = Thread.currentThread();
                t.setName("Admin Thread");
    
                // set thread priority to 1
                t.setPriority(1);
    
                // prints the current thread
                System.out.println("Thread = " + t);
    
                int count = Thread.activeCount();
                System.out.println("currently active threads = " + count);
    
                Thread th[] = new Thread[count];
                // returns the number of threads put into the array
                Thread.enumerate(th);
    
                // prints active threads
            for (int i = 0; i < count; i++) {
                System.out.println(i + ": " + th[i]);
            }
        }
    

    will generate the following output in inteliJ:

    Thread = Thread[Admin Thread,1,main]
    currently active threads = 2
    0: Thread[Admin Thread,1,main]
    1: Thread[Monitor Ctrl-Break,5,main]
    

    You can run it in debug and notice that this thread isnt created. Therefore, this thread is only added during normal run.

    0 讨论(0)
提交回复
热议问题