Do I need to add some locks or synchronization if there is only one thread writing and several threads reading?

后端 未结 2 1110
感情败类
感情败类 2021-01-15 16:59

Say I have a global object:

class Global {
   public static int remoteNumber = 0;
}

There is a thread runs periodically to get new number f

2条回答
  •  隐瞒了意图╮
    2021-01-15 17:16

    Read threads can read old value for undetermined time, but in practice there no problem. Its because each thread has own copy of this variable. Sometimes they sync. You can use volatile keyword to remove this optimisation:

    public static volatile int remoteNumber = 0;
    

提交回复
热议问题