java中可重入鎖的學習總結

      常常看到網上的人說,可重入鎖一詞,可是老是沒怎麼了解,到底什麼是可重入鎖,一直是一個模糊的概念,下面來大體總結一下。java

可重入鎖:指的是同一個線程屢次試圖獲取它所佔有的鎖,請求會成功。當釋放鎖的時候,直到重入次數清零,鎖才釋放完畢。.net

      再以前的個人博客:java synchronized關鍵字的用法--對象鎖和類鎖線程

http://my.oschina.net/u/1540325/blog/682950code

裏面最後我貼了一個程序:對象

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方法是不須要再次獲取鎖的。blog

 

synchronized和lock都是可重入的鎖,能夠防止死鎖,相對於可重入的鎖有一種自旋鎖,後面再作研究。get

相關文章
相關標籤/搜索