Java:如何检查是否可以获得锁?

发布于 2024-11-09 16:37:08 字数 351 浏览 4 评论 0原文

如果我想确保对 Java 中的对象进行独占访问,我可以编写如下内容:

...
Zoo zoo = findZoo();
synchronized(zoo)
{
    zoo.feedAllTheAnimals();
    ...
}

Is there a way to check if an object current is located?如果另一个线程正在访问 zoo,我不希望我的线程等待。如果 zoo 未锁定,我希望我的线程获取锁并执行 synchronized 块;如果没有,我希望它跳过它。

我该怎么做?

If I want to ensure exclusive access to an object in Java, I can write something like this:

...
Zoo zoo = findZoo();
synchronized(zoo)
{
    zoo.feedAllTheAnimals();
    ...
}

Is there a way to check if an object is currently locked? I don't want my thread to wait if another thread is accessing zoo. If zoo is not locked, I want my thread to acquire the lock and execute the synchronized block; if not, I want it to skip it.

How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不顾 2024-11-16 16:37:08

您无法使用 Java 中嵌入的低级本机同步来做到这一点。但您可以使用并发包中提供的高级 API 来完成此操作。

Lock lock = new ReentrantLock();
....
//some days later
....
boolean isLocked = lock.tryLock();

You can't do it using the low-level native synchronization embedded in Java. But you can do it using the high-level APIs provided in the concurrent package.

Lock lock = new ReentrantLock();
....
//some days later
....
boolean isLocked = lock.tryLock();
辞慾 2024-11-16 16:37:08

您可以使用Lock.tryLock()。更具体地说, java .util.concurrent.locks.ReentrantLock

you can use Lock.tryLock(). more concretely, java.util.concurrent.locks.ReentrantLock

为人所爱 2024-11-16 16:37:08

您也可以手动进行。尽管您已经使用 ReentrantLock 得到了满意的答案;)

private boolean flag;
private final Object flagLock = new Object();
private final Object actualLock = new Object();

//...

boolean canAquireActualLock = false;
synchronized (flagLock) {
    if (!flag) {
        flag = canAquireActualLock = true;
    }
}
if (canAquireActualLock) {
    try {
        synchronized (actualLock) {

            // the code in actual lock...

        }
    } finally {
        synchronized (flagLock) { flag = false; }
    }
}

当然您可以使用方便的方法进行包装。

You may do it manually too. Although you already have satisfying answer with ReentrantLock ;)

private boolean flag;
private final Object flagLock = new Object();
private final Object actualLock = new Object();

//...

boolean canAquireActualLock = false;
synchronized (flagLock) {
    if (!flag) {
        flag = canAquireActualLock = true;
    }
}
if (canAquireActualLock) {
    try {
        synchronized (actualLock) {

            // the code in actual lock...

        }
    } finally {
        synchronized (flagLock) { flag = false; }
    }
}

Of course you could wrap with convenient methods.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文