標籤:stat not number keyword 方法 rac 成功 調用 code
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....
如果內建鎖不是可重新進入的,那麼這段代碼將發生死結。
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(); }}
Java多線程之深入理解synchronize關鍵字