How Synchronization works in Java?

后端 未结 8 597
广开言路
广开言路 2020-12-08 21:46

I have a doubt regarding Java Synchronization . I want to know if I have three Synchronized methods in my class and a thread acquires lock in one synchronized method other t

8条回答
  •  没有蜡笔的小新
    2020-12-08 22:24

    It is true and it does in this way. It is necessary as well to consistent the data of that object.

    Suppose that this validation is not there and there is a variable x which is being manipulated by 2 different synchronized method xxx() and yyy().

    so if Thread A gets lock of method xxx() which is manipulating x=5 and second thread B gets lock of method yyy() and manipulating x=-5 so in the end of method xxx() thread A is expecting x=5 but it will get x=0 that is wrong.

    Thats why it is implemented in this way.

提交回复
热议问题