本文介绍了将synchronized()与ReentrantLock.lock()混合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,执行 ReentrantLock.lock() ReetrantLock.unlock()使用相同的锁定机制 synchronized()

In Java, do ReentrantLock.lock() and ReetrantLock.unlock() use the same locking mechanism as synchronized()?

我的猜测是不,但我希望是错的。

My guess is "No," but I'm hoping to be wrong.

示例:

想象一下,线程1和线程2都可以访问:

Imagine that Thread 1 and Thread 2 both have access to:

ReentrantLock lock = new ReentrantLock();

线程1运行:

synchronized (lock) {
    // blah
}

线程2运行:

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

假设线程1首先到达其部分,然后在线程1完成之前到达线程2 :线程2会等待线程1离开 synchronized()块,还是会继续运行?

Assume Thread 1 reaches its part first, then Thread 2 before Thread 1 is finished: will Thread 2 wait for Thread 1 to leave the synchronized() block, or will it go ahead and run?

推荐答案

不,线程2可以 lock()即使线程1 已同步在同一个上。这就是不得不说:

No, Thread 2 can lock() even when Thread 1 is synchronized on the same lock. This is what the documentation has to say:

这篇关于将synchronized()与ReentrantLock.lock()混合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:23