Synchronized method does not work as expected

后端 未结 5 1481
广开言路
广开言路 2020-12-18 09:26

I have a variable which is shared by two threads. The two threads will do some operations on it. I don\'t know why the result of sharedVar is different every time I execute

5条回答
  •  有刺的猬
    2020-12-18 10:10

    When a thread is about to execute a 'synchronized' instance method, it aqcuires the lock on the Object(to be precise, lock on that object monitor).

    So in your case, Thread mt1 acquires lock on Object mt1 and Thread mt2 acquires lock on Object mt2 and they do not block each Other as the two threads are working on two different locks.

    And when two threads modify a shared variable concurrently(not synchronized way), the result is unpredictable.

    Well about the case of value 1000, for smaller inputs the interleaved execution might have resulted in correct result(luckily).

    Sol : remove the synchronized keyword from addOne method and make sharedVal as type of 'AtomicInteger'

提交回复
热议问题