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

Viewed 91

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?

1 Answers

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.

Related