【问题标题】:run() is never called by Thread.start() methodThread.start() 方法永远不会调用 run()
【发布时间】:2017-01-19 05:18:14
【问题描述】:

我写了一个小的多线程程序。

public class NewThread implements Runnable {
    Thread t;

    public NewThread() {
        t = new Thread(this, "Thread created by Thread Class.");
        System.out.println("Created by constuctor:"+ t);
        t.start(); // This will call run, because t has context as this
    }   

    @Override
    public void run() {     
        System.out.println("run() method called.");     
    }

    public static void main(String[] args) {
        new NewThread();
    }
}

这就是书中所说的写作方式。但是,我从来没有在控制台中得到 run() method called 语句。因此,似乎从未调用过run()。这怎么可能是真的?

编辑:是的,从构造函数启动线程是不好的做法,但这不会影响问题。 (我得到了很多反对票)

【问题讨论】:

  • 我强烈建议不要在构造函数中启动线程。除此之外,您无需等待新线程启动并且它没有机会打印任何内容 - 您需要 join() 它。
  • 你的问题到底是什么,你的代码返回这个结果由构造函数创建:Thread[Thread created by Thread Class.,5,main] run()方法被调用。
  • @YoucefLaidani 没有。它不会。结果是种族危险,结果未知。
  • 啊,好吧,你的问题不清楚
  • 不返回run() method called

标签: java multithreading constructor


【解决方案1】:

run() 永远不会被 Thread.start() 方法调用

您的代码实际上在我的系统上有效,但在您的系统上无效,这表明您有一个经典的竞争条件。

main() 内部,构造了NewThread,但Java 语言说它可以重新排序操作,以便构造函数中的操作可以在构造函数完成 之后发生。因此,main() 可能会在NewThread 实际启动之前完成,这可能导致 JVM 在不运行线程的情况下关闭。

由于指令重新排序,您不应该让线程在构造函数内部自动启动。见:Why not to start a thread in the constructor? How to terminate?

你应该这样做:

public NewThread() {
    t = new Thread(this, "Thread created by Thread Class.");
    System.out.println("Created by constuctor:" + t);
    // don't start here
}
public void start() {
    // start in another method
    t.start();
}
public void run() {     
    System.out.println("run() method called.");     
}
...

public static void main(String[] args) {
    NewThread nt = new NewThread();
    nt.start();
}

由于NewThread 与您的主线程(非守护程序)具有相同的守护程序状态,因此在nt.run() 完成之前,JVM 不会关闭。

【讨论】:

  • 有用的链接ibm.com/developerworks/library/j-jtp0618(把它放在这里供以后参考,因为你把它从答案中删除了。)
  • 谢谢@AnilBhaskar。我仍在寻找有关该主题的更好页面。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多