java可重入锁synchronized和ReentrantLock
什么就叫可重入锁?
可重入锁也叫可重复可递归调用的锁,同一线程外层函数获得锁之后,在进入内层方法的时候会自动获取锁,然后使用,无需等待去再次获取锁,并且不发生死锁(前提得是同一个对象或者class),这样的锁就叫做可重入锁。同一个线程每次进入一次,锁的计数器都自增1,所以要等到锁的计数器下降为0时才能释放锁。
可重入锁的意义之一在于防止死锁。
代码简单实现,synchronized实现
public class TestLock {
public static synchronized void say() {
System.out.println(Thread.currentThread().getName()+"\t invoke say");
eat();
}
public synchronized static void eat() {
System.out.println(Thread.currentThread().getName()+"\t invoke eat");
}
public static void main(String[] args) {
new Thread(()->{
say();
},"t1").start();
new Thread(()->{
say();
},"t2").start();
}
}
打印结果
ReentrantLock实现
public class TestLock2 {
private static Lock lock = new ReentrantLock();
public static void say() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName()+"\t invoke say");
eat();
} finally {
lock.unlock();
}
}
public static void eat() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName()+"\t invoke eat");
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
new Thread(()->{
say();
},"t1").start();
new Thread(()->{
say();
},"t2").start();
}
}
打印结果
可以看到,当方法eat也需要锁时,可以直接使用外层已经获取到的锁,而不用去等待重新获取锁。避免了去等待获取锁,从而造成死锁问题。
还没有评论,来说两句吧...