JAVA threads (different stacks) synchronization

后端 未结 8 1506
北恋
北恋 2021-01-05 22:19

I have a question regarding synchronization of code that is executed by several threads:

As far as I know each thread has its own stack, hence, non-static variables

8条回答
  •  隐瞒了意图╮
    2021-01-05 23:24

    On a same object instance, if your method is not synchronized, there is no guarantee that the same code is not executed twice in different threads --> havoc! Which is the correct value?

    At the minimum, you want to declare methods accessing a variable as synchronized. If you want more fine-grained control, you can use, for instance, a ReentrantReadWriteLock.

    Declaring a method synchronized synchronizes on the object instance, so this is safe.

提交回复
热议问题