JAVA threads (different stacks) synchronization

后端 未结 8 1508
北恋
北恋 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:22

    Local variables, primitives and references are implicitly thread-local. However, objects referenced can be shared and when a thread can modify a shared object it is highly likely you will need synchronised, a Lock or some other strategy to ensure thread safety.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题