Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute main thread method in child thread

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");
    }

}
like image 322
Vishwanath.M Avatar asked Jan 27 '26 14:01

Vishwanath.M


1 Answers

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()

    public class TestExample {
    
         public static void main(String[] args) {
    
            final TestExample  test = new TestExample();
    
           
            
          Thread t =  new Thread(new Runnable() {
    
                @Override
                public void run() {
    
                    System.out.println(Thread.currentThread().getName());
                    test.dance();
                }
            });
          t.setName("Child Thread");
          t.start();
    
        }
    
        public void dance() {
            System.out.println(Thread.currentThread().getName());
        }
    
        

}
like image 194
Kumar Vivek Mitra Avatar answered Jan 29 '26 09:01

Kumar Vivek Mitra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!