简体   繁体   English

在递归 java 方法中,每个方法调用都会导致一个新堆栈吗?

[英]In a recursive java method does each method call result in a new stack?

I understand that each thread will have it's own stack, so does that mean that each method will have it's own thread too?我知道每个线程都有自己的堆栈,这是否意味着每个方法也将拥有自己的线程?

No, each method has its own stack frame within the current thread's stack.不,每个方法在当前线程的堆栈中都有自己的堆栈

So if you had two threads, one calling method1() which calls method2(), and another calling methodA() which calls methodB() which calls methodC(), you'll end up with:所以如果你有两个线程,一个调用method1()调用method2(),另一个调用methodA()调用methodB()调用methodC(),你最终会得到:

Stack 1                    Stack2

                           methodC()
method2()                  methodB()
method1()                  methodA()

Note that there's also the possibility of tail recursion which allows a recursive call to replace the current stack frame instead of creating a new one.请注意,也存在尾递归的可能性,它允许递归调用替换当前堆栈帧而不是创建新堆栈帧。

I does not, this is also the reason why you might get a StackOverflowError in cases when your recursion goes too deep.我没有,这也是在递归太深的情况下可能会出现StackOverflowError的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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