简体   繁体   中英

Why is this my attempt of spawning endless Threads stopping at 4?

I have this simple code in Java 8:

class ThreadTest {
    void threadTest() {
        new Thread(this::threadTest).start();
        System.out.println(Thread.activeCount());
    }

    public static void main(String[] args) {
        new ThreadTest().threadTest();
    }
}

and I was pretty much expecting to see very large numbers getting printed. All I see in the console is:

4
4
4
4
4
4
4
4
4

I said maybe I am not able to see others for whatever reason and modified the code as below:

class ThreadTest {
    void threadTest() {
        new Thread(this::threadTest).start();
        if (Thread.activeCount() > 4) {
            System.out.println(Thread.activeCount());
        }
    }

    public static void main(String[] args) {
        new ThreadTest().threadTest();
    }
}

and now nothing gets printed.

What am I missing here?

Once your thread reaches the end of its execution (in your case, the end of the threadTest() method), it is no longer an active thread.

If you add an excessively long Thread.sleep in your method, you will see this active thread count increase further.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM