Synchronized block and monitor objects

前端 未结 3 510
名媛妹妹
名媛妹妹 2021-02-08 15:19

Hi can someone explain if the in the following code the synchronized code will restrict access to the threads. If yes how is it different from, if we have used \"this\" as a mon

3条回答
  •  离开以前
    2021-02-08 16:06

    synchronized(this)
    

    means only locking on this object instance. If you have multiple threads using this object instance and calling this method, only one thread at a time can access within the synchronized block.

    synchronized(msg) 
    

    means the locking is base on the msg string. If you have multiple threads using this object instance and calling this method, multiple threads can access within this synchronized block if the msg are different instance. Beware of how Java deal with String equality to avoid the surprising effect tho.

提交回复
热议问题