可重入锁,也叫做递归锁,指的是同一线程外层函数获得锁之后 ,内层递归函数仍然可以获取该锁的代码,但不受影响。
可重入锁使用示例
public class SynchronizedSample implements Runnable {
public synchronized void funA() { // 执行funA方法,需要获取对象锁
// synchronized属于可重入锁,进入funA方法后,拥有了对象锁,所以执行方法funB方法时不受影响。
System.out.println(Thread.currentThread().getName() + " " + Thread.currentThread().getId());
funB();
}
public synchronized void funB() { // 执行funB方法,需要获取对象锁
System.out.println(Thread.currentThread().getName() + " " + Thread.currentThread().getId());
}
@Override
public void run() {
funA();
}
public static void main(String[] args) {
SynchronizedSample ss = new SynchronizedSample();
new Thread(ss).start();
new Thread(ss).start();
new Thread(ss).start();
}
}
public class ReentrantLockSample implements Runnable {
ReentrantLock lock = new ReentrantLock();
public void funA() { // 执行funA方法,需要获取对象锁
lock.lock(); // 第一次获取锁
System.out.println(Thread.currentThread().getName() + " " + Thread.currentThread().getId());
funB(); // 该方法会第二次获取锁
lock.unlock();
}
public void funB() { // 执行funB方法,需要获取对象锁
lock.lock();
System.out.println(Thread.currentThread().getName() + " " + Thread.currentThread().getId());
lock.unlock();
}
@Override
public void run() {
funA();
}
public static void main(String[] args) {
ReentrantLockSample rs = new ReentrantLockSample();
new Thread(rs).start();
new Thread(rs).start();
new Thread(rs).start();
}
}
程序输出结果
Thread-1 14
Thread-1 14
Thread-2 15
Thread-2 15
Thread-0 13
Thread-0 13
相同点
不同点
使用建议
在一些内置锁sychronized无法满足需求的情况下,ReentrantLock可作为高级工具使用。否则,应该优先考虑使用sychronized。
/**
* 欢迎评论、留言、发表看法。谢谢!
*/
原文:https://www.cnblogs.com/mengHeJiuQIan/p/11158012.html