static variables in multithreading

后端 未结 4 767
耶瑟儿~
耶瑟儿~ 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:12

    Because first part of question is already answered, I will try to answer on second question.

    I know that static variables should be used within synchronized block. but why?

    Because if you don't use atomic, operations with variables are not atomic. That's why you should block variables while working with them. But in real world, you can use volatile keyword, that will guarantee you, that threads will have actual values of variable.

提交回复
热议问题