简体   繁体   中英

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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