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

后端 未结 3 1538
故里飘歌
故里飘歌 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: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.

提交回复
热议问题