我最近在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);
}
}
}