2019独角兽企业重金招聘Python工程师标准>>>
经常看到网上的人说,可重入锁一词,但是总是没怎么了解,到底什么是可重入锁,一直是一个模糊的概念,下面来大致总结一下。
可重入锁:指的是同一个线程多次试图获取它所占有的锁,请求会成功。当释放锁的时候,直到重入次数清零,锁才释放完毕。
再之前的我的博客:java synchronized关键字的用法--对象锁和类锁
http://my.oschina.net/u/1540325/blog/682950
里面最后我贴了一个程序:
public class MultiLock {public synchronized void f1(int count, String threadName) {if (count-- > 0) {Print.print(threadName + ":f1() calling f2() with count " + count);f2(count, threadName);}}public synchronized void f2(int count, String threadName) {if (count-- > 0) {Print.print(threadName + ":f2() calling f1() with count " + count);f1(count, threadName);}}public static void main(String[] args) throws Exception {final MultiLock multiLock = new MultiLock();new Thread() {public void run() {String name = Thread.currentThread().getName();multiLock.f1(10, name);}}.start();new Thread() {public void run() {String name = Thread.currentThread().getName();multiLock.f2(10, name);}}.start();}
}
输出结果如下:Thread-1:f2() calling f1() with count 9
Thread-1:f1() calling f2() with count 8
Thread-1:f2() calling f1() with count 7
Thread-1:f1() calling f2() with count 6
Thread-1:f2() calling f1() with count 5
Thread-1:f1() calling f2() with count 4
Thread-1:f2() calling f1() with count 3
Thread-1:f1() calling f2() with count 2
Thread-1:f2() calling f1() with count 1
Thread-1:f1() calling f2() with count 0
Thread-0:f1() calling f2() with count 9
Thread-0:f2() calling f1() with count 8
Thread-0:f1() calling f2() with count 7
Thread-0:f2() calling f1() with count 6
Thread-0:f1() calling f2() with count 5
Thread-0:f2() calling f1() with count 4
Thread-0:f1() calling f2() with count 3
Thread-0:f2() calling f1() with count 2
Thread-0:f1() calling f2() with count 1
Thread-0:f2() calling f1() with count 0
当时就觉得奇怪,在f1()里面调用了synchronized的f2(),当时只知道是可以,不知道具体原因,现在明白了,因为synchronized是可重入的锁,所以同一个对象的synchronized的方法调用另外一个synchronized方法是不需要再次获取锁的。
synchronized和lock都是可重入的锁,可以防止死锁,相对于可重入的锁有一种自旋锁,后面再做研究。