面試官:對併發熟悉嗎?說說Synchronized及實現原理

一、Synchronized的基本使用

Synchronized是Java中解決併發問題的一種最常用的方法,也是最簡單的一種方法。

Synchronized的作用主要有三個:

  • 確保線程互斥的訪問同步代碼
  • 保證共享變量的修改能夠及時可見
  • 有效解決重排序問題。

從語法上講,Synchronized總共有三種用法:

  • 修飾普通方法
  • 修飾靜態方法
  • 修飾代碼塊

接下來我就通過幾個例子程序來說明一下這三種使用方式(爲了便於比較,三段代碼除了Synchronized的使用方式不同以外,其他基本保持一致)。

1、沒有同步的情況:

代碼段一:

package com.paddx.test.concurrent;

public class SynchronizedTest {
    public void method1(){
        System.out.println("Method 1 start");
        try {
            System.out.println("Method 1 execute");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Method 1 end");
    }

    public void method2(){
        System.out.println("Method 2 start");
        try {
            System.out.println("Method 2 execute");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Method 2 end");
    }

    public static void main(String[] args) {
        final SynchronizedTest test = new SynchronizedTest();

        new Thread(new Runnable() {
            @Override
            public void run() {
                test.method1();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                test.method2();
            }
        }).start();
    }
}

執行結果如下,線程1和線程2同時進入執行狀態,線程2執行速度比線程1快,所以線程2先執行完成,這個過程中線程1和線程2是同時執行的。

Method 1 startMethod 1 executeMethod 2 startMethod 2 executeMethod 2 endMethod 1 end

2、對普通方法同步:

代碼段二:

package com.paddx.test.concurrent;

public class SynchronizedTest {
    public synchronized void method1(){
        System.out.println("Method 1 start");
        try {
            System.out.println("Method 1 execute");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Method 1 end");
    }

    public synchronized void method2(){
        System.out.println("Method 2 start");
        try {
            System.out.println("Method 2 execute");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Method 2 end");
    }

    public static void main(String[] args) {
        final SynchronizedTest test = new SynchronizedTest();

        new Thread(new Runnable() {
            @Override
            public void run() {
                test.method1();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                test.method2();
            }
        }).start();
    }
}

執行結果如下,跟代碼段一比較,可以很明顯的看出,線程2需要等待線程1的method1執行完成才能開始執行method2方法。

Method 1 startMethod 1 executeMethod 1 endMethod 2 startMethod 2 executeMethod 2 end

3、靜態方法(類)同步

代碼段三:

package com.paddx.test.concurrent;

 public class SynchronizedTest {
     public static synchronized void method1(){
         System.out.println("Method 1 start");
         try {
             System.out.println("Method 1 execute");
             Thread.sleep(3000);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
         System.out.println("Method 1 end");
     }

     public static synchronized void method2(){
         System.out.println("Method 2 start");
         try {
             System.out.println("Method 2 execute");
             Thread.sleep(1000);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
         System.out.println("Method 2 end");
     }

     public static void main(String[] args) {
         final SynchronizedTest test = new SynchronizedTest();
         final SynchronizedTest test2 = new SynchronizedTest();

         new Thread(new Runnable() {
             @Override
             public void run() {
                 test.method1();
             }
         }).start();

         new Thread(new Runnable() {
             @Override
             public void run() {
                 test2.method2();
             }
         }).start();
     }
 }

執行結果如下,對靜態方法的同步本質上是對類的同步(靜態方法本質上是屬於類的方法,而不是對象上的方法),所以即使test和test2屬於不同的對象,但是它們都屬於SynchronizedTest類的實例,所以也只能順序的執行method1和method2,不能併發執行。

Method 1 startMethod 1 executeMethod 1 endMethod 2 startMethod 2 executeMethod 2 end

4、代碼塊同步

代碼段四:

package com.paddx.test.concurrent;

public class SynchronizedTest {
    public void method1(){
        System.out.println("Method 1 start");
        try {
            synchronized (this) {
                System.out.println("Method 1 execute");
                Thread.sleep(3000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Method 1 end");
    }

    public void method2(){
        System.out.println("Method 2 start");
        try {
            synchronized (this) {
                System.out.println("Method 2 execute");
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Method 2 end");
    }

    public static void main(String[] args) {
        final SynchronizedTest test = new SynchronizedTest();

        new Thread(new Runnable() {
            @Override
            public void run() {
                test.method1();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                test.method2();
            }
        }).start();
    }
}

執行結果如下,雖然線程1和線程2都進入了對應的方法開始執行,但是線程2在進入同步塊之前,需要等待線程1中同步塊執行完成。

Method 1 startMethod 1 executeMethod 2 startMethod 1 endMethod 2 executeMethod 2 end

二、Synchronized 原理

如果對上面的執行結果還有疑問,也先不用急,我們先來了解Synchronized的原理,再回頭上面的問題就一目瞭然了。我們先通過反編譯下面的代碼來看看Synchronized是如何實現對代碼塊進行同步的:

package com.paddx.test.concurrent;

public class SynchronizedDemo {
    public void method() {
        synchronized (this) {
            System.out.println("Method 1 start");
        }
    }
}

反編譯結果:

面試官:對併發熟悉嗎?說說Synchronized及實現原理

 

關於這兩條指令的作用,我們直接參考JVM規範中描述:

monitorenter :

Each object is associated with a monitor. A monitor is locked if and only if it has an owner. The thread that executes monitorenter attempts to gain ownership of the monitor associated with objectref, as follows:

If the entry count of the monitor associated with objectref is zero, the thread enters the monitor and sets its entry count to one. The thread is then the owner of the monitor.

If the thread already owns the monitor associated with objectref, it reenters the monitor, incrementing its entry count.

If another thread already owns the monitor associated with objectref, the thread blocks until the monitor's entry count is zero, then tries again to gain ownership.

這段話的大概意思爲:

每個對象有一個監視器鎖(monitor)。當monitor被佔用時就會處於鎖定狀態,線程執行monitorenter指令時嘗試獲取monitor的所有權,過程如下:

  • 如果monitor的進入數爲0,則該線程進入monitor,然後將進入數設置爲1,該線程即爲monitor的所有者。
  • 如果線程已經佔有該monitor,只是重新進入,則進入monitor的進入數加1.
  • 如果其他線程已經佔用了monitor,則該線程進入阻塞狀態,直到monitor的進入數爲0,再重新嘗試獲取monitor的所有權。

monitorexit: 

The thread that executes monitorexit must be the owner of the monitor associated with the instance referenced by objectref.The thread decrements the entry count of the monitor associated with objectref. If as a result the value of the entry count is zero, the thread exits the monitor and is no longer its owner. Other threads that are blocking to enter the monitor are allowed to attempt to do so.

這段話的大概意思爲:

執行monitorexit的線程必須是objectref所對應的monitor的所有者。

指令執行時,monitor的進入數減1,如果減1後進入數爲0,那線程退出monitor,不再是這個monitor的所有者。其他被這個monitor阻塞的線程可以嘗試去獲取這個 monitor 的所有權。

通過這兩段描述,我們應該能很清楚的看出Synchronized的實現原理,Synchronized的語義底層是通過一個monitor的對象來完成,其實wait/notify等方法也依賴於monitor對象,這就是爲什麼只有在同步的塊或者方法中才能調用wait/notify等方法,否則會拋出java.lang.IllegalMonitorStateException的異常的原因。

我們再來看一下同步方法的反編譯結果:

源代碼:

package com.paddx.test.concurrent;

public class SynchronizedMethod {
    public synchronized void method() {
        System.out.println("Hello World!");
    }
}

反編譯結果:

面試官:對併發熟悉嗎?說說Synchronized及實現原理

 

從反編譯的結果來看,方法的同步並沒有通過指令monitorenter和monitorexit來完成(理論上其實也可以通過這兩條指令來實現),不過相對於普通方法,其常量池中多了ACC_SYNCHRONIZED標示符。

JVM就是根據該標示符來實現方法的同步的:當方法調用時,調用指令將會檢查方法的 ACC_SYNCHRONIZED 訪問標誌是否被設置,如果設置了,執行線程將先獲取monitor,獲取成功之後才能執行方法體,方法執行完後再釋放monitor。

在方法執行期間,其他任何線程都無法再獲得同一個monitor對象。其實本質上沒有區別,只是方法的同步是一種隱式的方式來實現,無需通過字節碼來完成。

三、運行結果解釋

有了對Synchronized原理的認識,再來看上面的程序就可以迎刃而解了。

1、代碼段2結果:

雖然method1和method2是不同的方法,但是這兩個方法都進行了同步,並且是通過同一個對象去調用的,所以調用之前都需要先去競爭同一個對象上的鎖(monitor),也就只能互斥的獲取到鎖,因此,method1和method2只能順序的執行。

2、代碼段3結果:

雖然test和test2屬於不同對象,但是test和test2屬於同一個類的不同實例,由於method1和method2都屬於靜態同步方法,所以調用的時候需要獲取同一個類上monitor(每個類只對應一個class對象),所以也只能順序的執行。

3、代碼段4結果:

對於代碼塊的同步實質上需要獲取Synchronized關鍵字後面括號中對象的monitor,由於這段代碼中括號的內容都是this,而method1和method2又是通過同一的對象去調用的,所以進入同步塊之前需要去競爭同一個對象上的鎖,因此只能順序執行同步塊。

四 總結

Synchronized是Java併發編程中最常用的用於保證線程安全的方式,其使用相對也比較簡單。但是如果能夠深入瞭解其原理,對監視器鎖等底層知識有所瞭解,一方面可以幫助我們正確的使用Synchronized關鍵字,另一方面也能夠幫助我們更好的理解併發編程機制,有助我們在不同的情況下選擇更優的併發策略來完成任務。對平時遇到的各種併發問題,也能夠從容的應對。

最新整理的Java技術乾貨文檔資料:【Java核心知識點整理】涵蓋29個Java核心技術詳解,JVM,Redis,Nginx,Spring Boot,Spring Cloud,Kafka,併發編程,Tomcat,MyBatis,BAT面試題,Java技術精講視頻等。轉發+關注,私信回覆“乾貨”即可獲得免費領取方式。

掌握了這些知識點,面試時在候選人中又可以奪目不少,暴擊9999點。機會都是留給有準備的人,只有充足的準備,纔可能讓自己可以在候選人中脫穎而出。
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章