Java synchronize statement around a lock

ぃ、小莉子 提交于 2019-12-13 15:26:56

问题


I was wondering if

synchronize (lock) {
    ... 
}

Where lock is an instance of java.util.concurrent.locks.Lock, treats lock like any other object or as the try-finally idiom i.e.

 lock.lock(); 
 try {
     ... 
 } finally { 
    lock.unlock();
 }

回答1:


Lock documentation:

Note that Lock instances are just normal objects and can themselves be used as the target in a synchronized statement. Acquiring the monitor lock of a Lock instance has no specified relationship with invoking any of the lock() methods of that instance. It is recommended that to avoid confusion you never use Lock instances in this way, except within their own implementation.

So basically, it's treated as any other object. And, don't do that.




回答2:


It will treat the lock just like any other object.




回答3:


The lock statement in the C# programming language can be applied to restrict access to a specific part of code to only one thread at a time.



来源:https://stackoverflow.com/questions/1046193/java-synchronize-statement-around-a-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!