4

In Java Concurrency in Practice there is a sample that made me confused:

public class Novisibility {
    private static boolean ready;
    private static int number;

    private static class ReaderThread implements Runnable {

        public void run() {
            while (!ready) {
                Thread.yield();
            }
            System.out.println(number);
        }
    }

    public static void main(String[] args) {
        System.out.println("0");
        new Thread(new ReaderThread()).run();
        System.out.println("1");
        number = 42;
        System.out.println("2");
        ready = true;
        System.out.println("3");
    }
}

I can understand reordering makes the loop to never break, but I can't understand why "1", "2" and "3" are never printed to console. Could any body help?

Óscar López
  • 232,561
  • 37
  • 312
  • 386
Amir Pashazadeh
  • 7,170
  • 3
  • 39
  • 69

1 Answers1

7

You don't spawn a new thread but run it in the current one. Use the start() method instead.

Since you run() executes on the main thread and that method runs in an endless loop you'll never reach the System.out.println() statements (and neither do you reach ready = true;).

From the JavaDoc on run():

If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.

And start():

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

Thomas
  • 87,414
  • 12
  • 119
  • 157