Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

后端 未结 23 2004
北荒
北荒 2020-11-22 04:29

Can any one tell me the advantage of synchronized method over synchronized block with an example?

23条回答
  •  误落风尘
    2020-11-22 04:51

    The main difference is that if you use a synchronized block you may lock on an object other than this which allows to be much more flexible.

    Assume you have a message queue and multiple message producers and consumers. We don't want producers to interfere with each other, but the consumers should be able to retrieve messages without having to wait for the producers. So we just create an object

    Object writeLock = new Object();
    

    And from now on every time a producers wants to add a new message we just lock on that:

    synchronized(writeLock){
      // do something
    }
    

    So consumers may still read, and producers will be locked.

提交回复
热议问题