Java: how to check whether a lock can be acquired?

If I want to ensure exclusive access to objects in Java, I can write this:

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

Is there any way to check whether the object is currently locked? If another thread is visiting the zoo, I don't want my thread to wait If the zoo is not locked, I want my thread to acquire the lock and execute the synchronization block; If not, I want it to skip it

What shall I do?

Solution

You cannot use low - level native synchronization embedded in Java However, you can do this using the advanced APIs provided in the concurrency package

Lock lock = new reentrantlock();
....
//some days later
....
boolean isLocked = lock.tryLock();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>