1

我最近在 Java 中观察到(在实现深度递归函数调用时),线程的堆栈大小大于进程。我的意思是,例如,线程可以执行大约 30,000 次递归调用,而没有线程的程序只能对同一函数进行 10,000 次递归调用。

任何人都可以建议为什么会这样?

为了更好地理解和上下文,请尝试按原样运行 Java 代码并查看控制台上的消息打印输出......

package com.java.concept;

/**
 * This provides a mechanism to increase the call stack size, by starting the thread in the caller we can increase it
 * Result were 3 times higher
 */
public class DeepRecursionCallStack {
    private static int level = 0;

    public static long fact(int n) {
        level++;
        return n < 2 ? n : n * fact(n - 1);
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(null, null, "DeepRecursionCallStack", 1000000) {
            @Override
            public void run() {
                try {
                    level = 0;
                    System.out.println(fact(1 << 15));
                } catch (StackOverflowError e) {
                    System.err.println("New thread : true recursion level was " + level);
                    System.err.println("New thread : reported recursion level was "
                            + e.getStackTrace().length);
                }
            }

        };
        t.start();
        t.join();

        try {
            level = 0;
            System.out.println(fact(1 << 15));
        } catch (StackOverflowError e) {
            System.err.println("Main code : true recursion level was " + level);
            System.err.println("Main code : reported recursion level was "
                    + e.getStackTrace().length);
        }
    }

}
4

0 回答 0