如何检查是否可以获取锁

如何检查是否可以获取锁

本文介绍了Java:如何检查是否可以获取锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要确保以Java独占访问对象,可以编写如下内容:

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();
    ...
}

是否可以检查对象当前是否被锁定?如果另一个线程正在访问zoo,我不希望我的线程等待.如果zoo未锁定,我希望我的线程获取该锁并执行synchronized块;如果没有,我希望它跳过它.

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.

我该怎么做?

推荐答案

您不能使用Java中嵌入的低级本机同步来做到这一点.但是您可以使用并发包中提供的高级API来做到这一点.

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();

这篇关于Java:如何检查是否可以获取锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:24