一般意义上的可重入锁就是 ReentrantLock
广义上的可重入锁是指:
可重入锁,也叫做递归锁,指的是同一线程 外层函数获得锁之后 ,内层递归函数仍然有获取该锁的代码,但不受影响。
在 JAVA 环境下 ReentrantLock 和 synchronized 都是 可重入锁
代码:
- public class Main {
- public static void main(String[] args) {
- Test ss=new Test();
- new Thread(ss).start();
- new Thread(ss).start();
- new Thread(ss).start();
- }
- }
- class Test implements Runnable{
- public synchronized void get(){
- System.out.println(Thread.currentThread().getId());
- set();
- }
- public synchronized void set(){
- System.out.println(Thread.currentThread().getId());
- }
- @Override
- public void run() {
- get();
- }
- }
View Code
- 11
- 11
- 13
- 13
- 12
- 12
- import java.util.concurrent.locks.ReentrantLock;
- public class Main {
- public static void main(String[] args) {
- Test ss=new Test();
- new Thread(ss).start();
- new Thread(ss).start();
- new Thread(ss).start();
- }
- }
- class Test implements Runnable {
- ReentrantLock lock = new ReentrantLock();
- public void get() {
- lock.lock();
- System.out.println(Thread.currentThread().getId());
- set();
- lock.unlock();
- }
- public void set() {
- lock.lock();
- System.out.println(Thread.currentThread().getId());
- lock.unlock();
- }
- @Override
- public void run() {
- get();
- }
- }
View Code
- 12
- 12
- 13
- 13
- 11
- 11
可以发现同一线程都输出了两次
可重入锁最大的作用是避免死锁
来源: