Strange behavior in Java concurrency without synchronization

In Java Concurrency in practice, there is a pattern that confused me:

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 understand that reordering causes the loop to never break, but I cannot understand why "1", "2", and "3" never print to the console. Can any organ help?

+4
source share
1 answer

You do not create a new thread, but start it in the current one. Use the start() method instead.

Since you run() is executed in the main thread and this method runs in an infinite loop, you will never reach the System.out.println() statements (and you will not reach ready = true; ).

From JavaDoc to run() :

If this thread was created using a separate Runnable, then this Runnable object 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 method to start this thread.

+7
source

Source: https://habr.com/ru/post/1392253/


All Articles