Vishwanath.M
Vishwanath.M

Reputation: 6317

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

}

Upvotes: 3

Views: 3438

Answers (2)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

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

}

Upvotes: 4

xiaofeng.li
xiaofeng.li

Reputation: 8587

It's going to be executed in the Child Thread. When you write a method, it belongs to a Class not a particular Thread.

Upvotes: 0

Related Questions