【问题标题】:Execute main thread method in child thread在子线程中执行主线程方法
【发布时间】:2012-07-12 03:35:33
【问题描述】:

我有一个名为 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");
    }

}

【问题讨论】:

  • 尝试将System.out.format("thread: %s\n", Thread.currentThread().getName()); 放入mainrun。你会得到你的答案。

标签: java multithreading


【解决方案1】:

试试这个...

1.方法dance属于TestExample类,不属于主线程。

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

3.它是执行 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());
        }
    
        

}

【讨论】:

    【解决方案2】:

    它将在子线程中执行。当你编写一个方法时,它属于一个类而不是一个特定的线程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2023-03-04
      相关资源
      最近更新 更多