在子线程中执行主线程方法

时间:2012-07-12 03:35:34

标签: java multithreading

我有一个名为Test Example的类,它有一个名为dance()的方法。在主线程中,如果我在子线程中调用dance()方法,会发生什么?我的意思是,该方法将在子线程或主线程中执行吗?

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

}

2 个答案:

答案 0 :(得分:4)

试试这个......

1。方法舞蹈属于Class TestExample,而不属于主线程。

2. 每当启动java应用程序时,JVM都会创建一个主线程,并放置    堆栈底部的main()方法,使其成为入口点,但如果您正在创建另一个线程并调用方法,那么它将在新创建的线程内运行。

第3。它是将执行dance()方法的Child线程。

请参阅下面的示例,其中我使用了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());
        }



}

答案 1 :(得分:0)

它将在Child Thread中执行。编写方法时,它属于Class而不是特定的Thread。

相关问题