2

我试图写一个程序来测试java中父/子线程的执行效果!为什么活动线程数低于 3?其他线程会发生什么。这让我觉得 Java 可以拥有数百万个线程,但其中只有少数是活动的。这是正确的还是有别的?

public class ManyThreadsTester {
    static int threadCount = 0;
    static class recursiveRunnable implements Runnable{

        @Override
        public void run() {
            System.out.println(threadCount);
            // Arrives up to infinity if the System.exit(0) statement is absent!
            try {
                System.out.println("Active threads before: " + Thread.activeCount());
                //Always prints 2
                Thread.sleep(40);
                threadCount++;
                new Thread(new recursiveRunnable()).start();
            } catch (InterruptedException ex) {
                Logger.getLogger(ManyThreadsTester.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("Active threads after: " + Thread.activeCount());
            //Always prints 3
        }


    }

    public static void main(String... args) throws InterruptedException{
        Thread th = new Thread(new recursiveRunnable());
        th.start();
        Thread.sleep(5000);
        System.out.print("FINAL ACTIVE THREAD COUNTS: " + Thread.activeCount());
        //prints 2
        System.exit(0);
    }
}
4

1 回答 1

3

因为你的线程在产生孩子后立即退出。如果您在最后添加延迟,您将获得更高的数字:

new Thread(new recursiveRunnable()).start();
Thread.sleep(10000);

输出:

...
Active threads before: 30
28
Active threads before: 31
29
Active threads before: 32
30
...
于 2013-11-14T21:25:17.227 回答