将synchronized()与ReentrantLock.lock()混合 [英] Mixing synchronized() with ReentrantLock.lock()

查看:183
本文介绍了将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:


请注意,Lock实例只是
普通对象,本身可以用
作为目标在同步
语句中。获取Lock实例的监视器锁
与调用该实例的任何
lock()方法没有指定的
关系。建议使用
以避免混淆
你从不以
方式使用Lock实例,除非在他们自己的
实现中。

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆