简体   繁体   中英

run() is never called by Thread.start() method

I have written a small multithreading program.

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

This is how the book says to write it. However, I never get the run() method called statement in the console. Thus, it seems run() is never called. How can this be true?

Edit: Yes, it is bad practice to start a Thread from constructor, but that is not affecting the question. (I am getting so many down votes for that)

run() is never called by Thread.start() method

You code actually works on my system but that it doesn't work on your's, demonstrates that you have a classic race condition.

Inside of main() , the NewThread is constructed but the Java language says that it can reorder operations so that the operations in a constructor can happen after the constructor finishes. So it is possible that main() might finish before the NewThread has actually been started which can result in the JVM shutting down without running the thread.

Because of instruction reordering, you should never have a thread auto-start itself inside of the constructor. See: Why not to start a thread in the constructor? How to terminate?

You should instead do:

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

Since the NewThread has the same daemon status as your main thread (which is non-daemon) the JVM will not shutdown until nt.run() completes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM