I am currently studying for a concurrent programming exam and don\'t understand why the output of this program is 43. Why is x = y + 1
executed before t.s
I would like to add that the code in the main method runs in the Main thread and Thread t doesn't block execution of Main in your example. That's why the line x = y + 1
might be executed faster than the body of the Thread t (as @davidxxx already pointed out).
You can observe different behavior if you add t.join()
after t.start():
...
t.start();
t.join();
In this situation, the Main thread will wait for the Thread t to complete and the output will be 1.