可重入锁
2018-03-05 本文已影响26人
南乡清水
可重入锁,也叫做递归锁,指的是同一线程 外层函数获得锁之后 ,内层递归函数仍然有获取该锁的代码,但不受影响。比如ReentrantLock 和synchronized 都是 可重入锁
直接放代码
public class SubService {
ReentrantLock lock = new ReentrantLock();
public void subService1() {
lock.lock();
System.out.println("thread = " + Thread.currentThread().getId() + " --subService1");
subService2();
lock.unlock();
}
public synchronized void subService2() {
System.out.println("thread = " + Thread.currentThread().getId() + " --subService2");
}
}
public class Service extends SubService {
public synchronized void service1(){
System.out.println("thread = " + Thread.currentThread().getId() + " --service1");
service2();
}
public synchronized void service2() {
System.out.println("thread = " + Thread.currentThread().getId() + " --service2");
service3();
}
public synchronized void service3() {
System.out.println("thread = " + Thread.currentThread().getId() + " --service3");
this.subService1();
}
}
public class MyThread extends Thread {
@Override
public void run() {
Service service = new Service();
service.service1();
}
public static void main(String[] args) throws Exception {
MyThread thread1 = new MyThread();
thread1.start();
MyThread thread2 = new MyThread();
thread2.start();
}
}
运行结果
image通过测试,可以得知 ReentrantLock 和synchronized锁是可以重入的,且在父子类继承环境中同样有效,如果该类型锁不可重入,则在调用service1()方法的时候,应该发生死锁,结果是同一线程的锁内部函数中锁可以重入。
来源 :
java多线程编程核心技术
Java锁的种类以及辨析(四):可重入锁 http://ifeve.com/java_lock_see4/