java-在子线程中执行主线程方法
我有一个称为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");
    }

}
最佳答案
尝试这个…

1. Dance方法属于Class TestExample类,而不属于Main线程.

2.每当启动Java应用程序时,JVM就会创建一个主线程,并放置一个
   main()方法位于堆栈的底部,使其成为入口点,但是如果要创建另一个线程并调用一个方法,则它将在新创建的线程内运行.

3.它的Child线程将执行dance()方法.

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



}
点击查看更多相关文章

转载注明原文:java-在子线程中执行主线程方法 - 乐贴网