【问题标题】:Thread name and calling run method twice线程名和两次调用run方法
【发布时间】:2014-12-25 16:33:56
【问题描述】:

我正在学习,我在示例测试中看到了以下内容。 我不太清楚为什么下面的代码会打印“First”。

当我调试时,似乎 MyRunnable.run 被调用了两次。 这是否意味着即使在其他情况下也总是调用两次 run 方法?

public class currentThreadName {

    public static void main(String[] args) {
        Thread.currentThread().setName("First");
        MyRunnable mr = new MyRunnable("MyRunnable");
        mr.run();       
    }

}

class MyRunnable implements Runnable {
    MyRunnable(String name) {
        new Thread(this, name).start();
    }
    public void run(){
        System.out.println(Thread.currentThread().getName());
    }
}

【问题讨论】:

    标签: java multithreading main runnable


    【解决方案1】:

    您正在调用 mr.run();new Thread(this, name).start();,所以是的,它运行了两次。

    我建议你只使用start 来执行你的新线程。为什么?

    因为如果你只是直接调用run(),它将在调用线程上执行(就像任何其他方法调用一样)。

    但是,如果您调用Thread.start(),它会实际上创建一个新线程,以便并行执行runnable 的run 方法。

    【讨论】:

    • Thnx 但为什么“Frist”总是先打印或在打印“MyRunnable”之前打印?当
      .start()
      被调用时,我们不知道它什么时候会被执行,这是真的吗?因为JVM不保证任何东西
    • "First" 首先打印,因为它在其余代码之前执行。您的第二个陈述是正确的,如果两个线程同时处于活动状态,则不能保证哪个会先运行。
    • 实例化你的runnable对象然后多次调用它的start方法可以吗?每次都会创建一个新线程吗?
    【解决方案2】:

    run 方法被调用了两次。

    一次调用是在MyRunnable 构造函数中调用start();这是在单独的线程中执行的。打印“MyRunnable”。

    不过,你也可以直接在main中调用run,在主线程中执行。这负责输出“First”,因为您将名称“First”分配给了主线程。

    通常,您不应该直接调用run;仅致电start。这将在新线程中调用run

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      • 2021-02-28
      • 1970-01-01
      • 2016-10-18
      相关资源
      最近更新 更多