Why is this code working without volatile?

前端 未结 2 1262
广开言路
广开言路 2021-01-13 13:56

I am new to Java, I am currently learning about volatile. Say I have the following code:

public class Test
{
    private static boolean b = fals         


        
2条回答
  •  太阳男子
    2021-01-13 14:32

    The volatile keyword guarantees that changes are visible amongst multiple threads, but you're interpreting that to mean that opposite is also true; that the absence of the volatile keyword guarantees isolation between threads, and there's no such guarantee.

    Also, while your code example is multi-threaded, it isn't necessarily concurrent. It could be that the values were cached per-thread, but there was enough time for the JVM to propagate the change before you printed the result.

提交回复
热议问题