Java synchronize statement around a lock

2019-07-16 08:25发布

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();
 }

3条回答
太酷不给撩
2楼-- · 2019-07-16 08:56

It will treat the lock just like any other object.

查看更多
Summer. ? 凉城
3楼-- · 2019-07-16 08:59

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.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-07-16 09:08

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.

查看更多
登录 后发表回答