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

來源:互聯網
上載者:User

標籤: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....
  • 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關鍵字

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.