Can volatile variable be defined as static in java?

后端 未结 5 1461
無奈伤痛
無奈伤痛 2021-02-01 04:36

Can I declare something like this??

static volatile boolean first=false;
5条回答
  •  一向
    一向 (楼主)
    2021-02-01 05:25

    yes, you can.

    static boolean first=false;
    

    When you are declaring a static variable, there will be only one copy for all the objects, no matter how many objects of the class are created. Each thread would have its own cached copy.

    If it is volatile, Thread should go to memory each time and gets the updated value of the variable.

    static volatile boolean first=false;
    

    It will

    force the thread to read each time the memory directly

    to find the value of the variable first.

提交回复
热议问题