📅  最后修改于: 2023-12-03 15:31:31.865000             🧑  作者: Mango
Java ReentrantLock is a class that provides a mutual exclusion synchronization mechanism. It is a lock that can be acquired multiple times by the same thread without causing a deadlock. It is used to protect critical sections of code that should only be accessed by one thread at a time.
To use ReentrantLock, you first need to create an instance of it:
ReentrantLock lock = new ReentrantLock();
To acquire the lock, use the lock()
method:
lock.lock();
This will block the current thread until the lock is available. Once the lock is acquired, the thread can proceed to access the critical section:
// critical section of code
To release the lock, use the unlock()
method:
lock.unlock();
This will release the lock, allowing other threads to acquire it.
Both ReentrantLock and synchronized
provide a way to protect critical sections of code. However, ReentrantLock provides additional features that are not available with synchronized
, such as:
lockInterruptibly()
method.tryLock(long timeout, TimeUnit unit)
method.lock()
method. This is called reentrant behavior.Here is an example of using ReentrantLock to protect a critical section of code:
import java.util.concurrent.locks.ReentrantLock;
public class Example {
private final ReentrantLock lock = new ReentrantLock();
public void criticalSection() {
lock.lock();
try {
// critical section of code
} finally {
lock.unlock();
}
}
}
ReentrantLock is a powerful tool for synchronizing access to critical sections of code. It provides features that are not available with synchronized
, such as interruptible locking and reentrant behavior. However, it is also more complex to use than synchronized
, so it should only be used when necessary.