Yes, Threads have their own stack. This is very interesting question, where interviewer tends to check your basic knowledge about how threads internally maintains their own stacks. I’ll be explaining you the concept by diagram.
Program used for demonstrating how threads implements their own stack >
class MyThread extends Thread{
public void run(){
System.out.println("in run() method");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
public static void main(String...args){
System.out.println("In main() method");
method1();
}
static void method1(){
MyThread obj=new MyThread();
obj.start();
}
}
/*OUTPUT
currentThreadName= main
in run() method
currentThreadName= Thread-1
*/
|
RELATED LINKS>
Thread basics >
What is thread in java
Thread states/ Thread life cycle in java
Difference between Process and Thread in java
Implementing Threads in java by implementing Runnable interface and extending Thread class
DeadLock and it’s detection >
Deadlock in multithreading - program to form DeadLock, solving DeadLock, measures to avoid Deadlock.
Important Thread methods (salient features, usage with programs)>