static variables in multithreading

后端 未结 4 772
耶瑟儿~
耶瑟儿~ 2021-01-02 07:04

I found that declaring a variable as static makes no sense in Multi-Threading. I assume that, this is because of every thread has its own

4条回答
  •  天涯浪人
    2021-01-02 07:17

    If you change a variable in a multithreaded environment, the new value may not neccessarily visibile as it might be cached. This is also true for static variables of course. If you don't use a synchronized block you might consider using volatile instead. This will also guaruantee that the various threads get an updated copy, without the need of synchronizing. Wether volatile is enough four your application depends on your requirements.

提交回复
热议问题