1. 程式人生 > >Java多線程之深入理解synchronize關鍵字

Java多線程之深入理解synchronize關鍵字

tracking 而不是 方法 獲得 content cal art track ()

synchronize鎖重入:

關鍵字synchronize擁有鎖重入的功能,也就是在使用synchronize時,當一個線程的得到了一個對象的鎖後,再次請求此對象是可以再次得到該對象的鎖。
當一個線程請求一個由其他線程持有的鎖時,發出請求的線程就會被阻塞,然而,由於內置鎖是可重入的,因此如果某個線程試圖獲得一個已經由她自己持有的鎖,那麽這個請求就會成功,“重入” 意味著獲取鎖的 操作的粒度是“線程”,而不是調用。

public class SyncDubbol {

    public synchronized void method1(){
        System.out.println("method1....");
        method2();
    }
    public synchronized void method2(){
        System.out.println("method2....");
        method3();
    }
    public synchronized void method3(){
        System.out.println("method3....");
    }

    public static void main(String[] args) {
        final SyncDubbol sd=new SyncDubbol();
        new Thread(new Runnable() {
            @Override
            public void run() {
                sd.method1();
            }
        }).start();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

上面的代碼雖然三個方法都是被synchronize修飾,但是在執行method1方法時已經得到對象的鎖,所以在執行method2方法時無需等待,直接獲得鎖,因此這個方法的執行結果是

method1....
method2....
method3....
  • 1
  • 2
  • 3

如果內置鎖不是可重入的,那麽這段代碼將發生死鎖。

public class Widget{
    public synchronized void dosomething(){
        System.out.println("dosomthing");
    }
}
public class LoggingWidget extends Widget{
    public synchronized void dosomething(){
        System.out.println("calling dosomthing");
        super.dosomething();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Java多線程之深入理解synchronize關鍵字