Anil Bhaskar - 11 months ago 61
Java Question

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

I have written a small MultiThreading program.

public class NewThread implements Runnable{

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) {
}
}


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

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?

public NewThread() {

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