Happens-before rules in Java Memory Model

前端 未结 5 684
迷失自我
迷失自我 2021-01-18 10:21

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

5条回答
  •  礼貌的吻别
    2021-01-18 11:03

    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.

提交回复
热议问题