What is the purpose of passing parameter to synchronized block?

后端 未结 2 1517
春和景丽
春和景丽 2020-12-23 21:53

I know that

When you synchronize a block of code, you specify which object\'s lock you want to use as the lock, so you could, for example, use some

2条回答
  •  失恋的感觉
    2020-12-23 22:54

    if anyways synchronized block stops two threads from entering the critical section simultaneously. Then why there is a need of passing an argument?

    Synchronized block decides which threads to stop based on the object that you pass to it. The object that you pass serves as the identifier of the monitor section guarded by the synchronized block.

    You may have many monitor sections in your program, all of which could be executed concurrently with each other. For example, if you have two unrelated collections that must be accessed concurrently, you can set up separate monitor sections for each collection. This way threads would be stopped only when other threads are already accessing the same collection; two different threads accessing two different collections would be allowed to proceed concurrently.

    Your first example is non-trivial. The reason it works is that the string object is initialized to a string literal. Due to literal's interning, all threads entering the function will obtain the same String object, so the synchronized block will properly guard the monitor section.

提交回复
热议问题