I have a class called Test Example and it has one method called dance(). In the main thread, if I call the dance() method inside the child thread, what happens? I mean, will that method execute in the child thread or the main thread?
public class TestExample {
public static void main(String[] args) {
final TestExample test = new TestExample();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hi Child Thread");
test.dance();
}
}).start();
}
public void dance() {
System.out.println("Hi Main thraed");
}
}
Try this…
1. The method dance belongs to the Class TestExample, NOT to the Main thread.
2. Whenever a java application is started then JVM creates a Main Thread, and places the
main() methods in the bottom of the stack, making it the entry point, but if you are creating another thread and calling a method, then it runs inside that newly created thread.
3. Its the Child thread that will execute the dance() method.
See this below example, where i have used
Thread.currentThread().getName()