是否使重入锁定为静态并使其成为互斥锁? [英] Does making a Reentrant Lock static and make it a mutex?

查看:98
本文介绍了是否使重入锁定为静态并使其成为互斥锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Brian Goetz的书Java Concurrency in Practice中,他的Reentrant锁定示例编程如下:

In Brian Goetz's book, Java Concurrency in Practice, his example of a Reentrant lock is programmed like this:

Lock lock = new ReentrantLock();

但是,我很想知道是否将上述代码更改为:

However, I am curious to know if changing the above code to:

private static final Lock lock = new ReentrantLock();

导致锁现在充当互斥锁,或者它是不必要且多余的。

causes the lock to now act as a mutex, or if it is unnecessary and redundant.

因此,如果将锁定为私有,静态和最终,此代码的功能是否会发生变化?

Thus, does the functionality of this code change if the lock is made private, static, and final?

lock.lock();
try {
    //method stuff
} finally {
    lock.unlock();
}

提前谢谢大家。
Matt

Thank you all in advance. Matt

推荐答案

是。

final private 当然没有影响力,但 static 意味着所有实例共享相同的锁。

final and private have no influence, of course, but static means that all instances share the same lock.

因此,如果您有两个实例,则代码块不能同时由两个线程执行。

So if you have two instances, the code block can't be executed by two threads at the same time.

如果锁不是静态的,则每个实例都有自己的锁。这意味着更多线程可以同时运行代码(当然,取决于它们工作的实例)。

If the lock isn't static, each instance gets its own lock. That means that more threads can run the code at the same time (depending on which instance they work, of course).

这篇关于是否使重入锁定为静态并使其成为互斥锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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