1.相对于synchronized具备的特点:
1) 可打断:避免死等2)可以设置超时时间:避免死等3)可以设置为公平锁:防止饥饿4)支持多个条件变量:可以指定唤醒某个特定线程5)需要手动释放锁:如果执行过程中出现异常,并不会自动释放锁, 需要写finally块手动释放锁
2. 可重入:
设置ReentrantLock为类的静态变量,在main线程中调用m1()方法,m1()方法加锁reentrantlock.lock(),m1中又调用m2(),m2也加锁,m2()调用m3(),m3方法中也加锁。
static ReentrantLock reentrantLock = new ReentrantLock();
public static void main(String[] args) {
method1();
}
public static void method1() {
reentrantLock.lock();
try {
log.debug("execute method1");
method2();
} finally {
reentrantLock.unlock();
}
}
public static void method2() {
reentrantLock.lock();
try {
log.debug("execute method2");
method3();
} finally {
reentrantLock.unlock();
}
}
public static void method3() {
reentrantLock.lock();
try {
log.debug("execute method3");
} finally {
reentrantLock.unlock();
}
}
运行结果:说明ReentrantLock是可重入锁