简体   繁体   English

使用ReentrantLock可靠吗?

[英]Is using ReentrantLock reliable as synchronized?

I searched a lot but was confused with the process of 'ReentrantLock' and normal 'synchronized' . 我进行了很多搜索,但对“ ReentrantLock”和正常的“ synchronized”过程感到困惑。

For example( 1 ): 例如( 1 ):

Object obj = new Object();

synchronized(obj){
//lock is guaranteed to be acquired 
}

example( 2 ) 例子( 2

Lock lock = new ReentrantLock();
lock.lock(); //problem here
try{
//dostuff
}
finally{
lock.unlock();
}

My question is: 我的问题是:

In example 1 : it is guaranteed to acquire a lock on the object using the synchronized keyword. 在示例1中 :可以确保使用synced关键字获取对象上的锁。

But

In example 2 : is it guaranteed that the lock will be acquired using the lock.lock() method?? 在示例2中是否可以确保使用lock.lock()方法获取锁? or will the thread proceed to the next line for the execution?? 还是线程将继续执行下一行? without acquiring the lock. 不获取锁。

I doubt it because, using threads had resulted in unexpected outcomes for me many times. 我对此表示怀疑,因为使用线程多次导致了意外结果。

Only one thread will acquire the lock: this is the contract of ReentrantLock . 只有一个线程将获得该锁:这是ReentrantLock的合同。

Therefore your example 2 is perfectly thread safe. 因此,示例2完全是线程安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM