java如何实现可重入
Java 可重入锁的实现方式
Java 中实现可重入锁主要有两种方式:通过 synchronized 关键字或使用 ReentrantLock 类。可重入锁允许同一个线程多次获取同一把锁,避免死锁。
使用 synchronized 关键字
synchronized 是 Java 内置的可重入锁机制,隐式支持可重入性。
public class ReentrantExample {
public synchronized void outer() {
System.out.println("Outer method");
inner(); // 调用另一个 synchronized 方法
}
public synchronized void inner() {
System.out.println("Inner method");
}
public static void main(String[] args) {
ReentrantExample example = new ReentrantExample();
example.outer(); // 同一个线程可以重入锁
}
}
使用 ReentrantLock 类
ReentrantLock 是显式锁,提供了更灵活的锁控制。

import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockExample {
private final ReentrantLock lock = new ReentrantLock();
public void outer() {
lock.lock();
try {
System.out.println("Outer method");
inner(); // 重入锁
} finally {
lock.unlock();
}
}
public void inner() {
lock.lock();
try {
System.out.println("Inner method");
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ReentrantLockExample example = new ReentrantLockExample();
example.outer();
}
}
可重入锁的核心特性
- 重入计数:每次锁被获取时计数加 1,释放时计数减 1,计数为 0 时锁完全释放。
- 避免死锁:同一线程多次获取锁不会阻塞自身。
- 公平性选项:
ReentrantLock支持公平锁和非公平锁模式。
选择建议
- 简单场景:优先使用
synchronized,代码简洁且自动管理锁的释放。 - 复杂场景:使用
ReentrantLock,支持超时、中断和公平性控制。






