Anil Bhaskar Anil Bhaskar - 2 months ago 8
Java Question

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




That is how the book says. I am surely missing some silly thing here, need help from a multithreading expert.

Answer

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 instructor 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);
}
...

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 run() completes.

Comments