Synchronized看這一篇就足夠了(吐血超詳細總結)


看了網上很多關於Synchronized的講解,但是感覺講解的都不是很透徹,今天博主也來寫一篇關於Synchronized的文章,希望能幫助大家更好的理解Synchronized~

一、為什么要使用synchronized

在並發編程中存在線程安全問題,主要原因有:1.存在共享數據 2.多線程共同操作共享數據。關鍵字synchronized可以保證在同一時刻,只有一個線程可以執行某個方法或某個代碼塊,同時synchronized可以保證一個線程的變化可見(可見性),即可以代替volatile。

二、實現原理

synchronized可以保證方法或者代碼塊在運行時,同一時刻只有一個方法可以進入到臨界區,同時它還可以保證共享變量的內存可見性

三、synchronized的三種應用方式

Java中每一個對象都可以作為鎖,這是synchronized實現同步的基礎:

  1. 普通同步方法(實例方法),鎖是當前實例對象 ,進入同步代碼前要獲得當前實例的鎖
  2. 靜態同步方法,鎖是當前類的class對象 ,進入同步代碼前要獲得當前類對象的鎖
  3. 同步方法塊,鎖是括號里面的對象,對給定對象加鎖,進入同步代碼庫前要獲得給定對象的鎖。

四、synchronized的作用

Synchronized是Java中解決並發問題的一種最常用最簡單的方法 ,他可以確保線程互斥的訪問同步代碼

五、舉栗子

1、synchronized作用於實例方法

①. 多個線程訪問同一個對象的同一個方法

public class synchronizedTest implements Runnable {
    //共享資源
    static int i =0;
    /**
     * synchronized 修飾實例方法
     */
    public synchronized void increase(){
        i++;
    }
    @Override
    public void run(){
        for (int j =0 ; j<10000;j++){
            increase();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        synchronizedTest test = new synchronizedTest();
        Thread t1 = new Thread(test);
        Thread t2 = new Thread(test);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(i);
    }
}

結果:

這里寫圖片描述

分析:當兩個線程同時對一個對象的一個方法進行操作,只有一個線程能夠搶到鎖。因為一個對象只有一把鎖,一個線程獲取了該對象的鎖之后,其他線程無法獲取該對象的鎖,就不能訪問該對象的其他synchronized實例方法,但是可以訪問非synchronized修飾的方法

②. 一個線程獲取了該對象的鎖之后,其他線程來訪問其他synchronized實例方法現象 舉栗

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(test::method1).start();

        new Thread(test::method2).start();
    }

}

結果:

這里寫圖片描述

分析:可以看出其他線程來訪問synchronized修飾的其他方法時需要等待線程1先把鎖釋放

③. 一個線程獲取了該對象的鎖之后,其他線程來訪問其他非synchronized實例方法現象 舉栗
去掉②中方法二的synchronized

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 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(test::method1).start();
        new Thread(test::method2).start();
    }

}

結果:

這里寫圖片描述

分析:當線程1還在執行時,線程2也執行了,所以當其他線程來訪問非synchronized修飾的方法時是可以訪問的

④. 當多個線程作用於不同的對象

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 test1 = new SynchronizedTest();
        final SynchronizedTest test2 = new SynchronizedTest();

        new Thread(test1::method1).start();

        new Thread(test2::method2).start();
    }

}

結果:

在這里插入圖片描述

分析:因為兩個線程作用於不同的對象,獲得的是不同的鎖,所以互相並不影響

此處思考一個問題:為什么分布式環境下synchronized失效?如何解決這種情況?

2、synchronized作用於靜態方法

public class synchronizedTest implements Runnable {
    //共享資源
    static int i =0;
    /**
     * synchronized 修飾實例方法
     */
    public static synchronized void increase(){
        i++;
    }
    @Override
    public void run(){
        for (int j =0 ; j<10000;j++){
            increase();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new synchronizedTest());
        Thread t2 = new Thread(new synchronizedTest());
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(i);
    }

結果:

這里寫圖片描述

分析:由例子可知,兩個線程實例化兩個不同的對象,但是訪問的方法是靜態的,兩個線程發生了互斥(即一個線程訪問,另一個線程只能等着),因為靜態方法是依附於類而不是對象的,當synchronized修飾靜態方法時,鎖是class對象。

3、synchronized作用於同步代碼塊

為什么要同步代碼塊呢?在某些情況下,我們編寫的方法體可能比較大,同時存在一些比較耗時的操作,而需要同步的代碼又只有一小部分,如果直接對整個方法進行同步操作,可能會得不償失,此時我們可以使用同步代碼塊的方式對需要同步的代碼進行包裹,這樣就無需對整個方法進行同步操作了。

 public class synchronizedTest implements Runnable {
    static synchronizedTest instance=new synchronizedTest();
    static int i=0;
    @Override
    public void run() {
        //省略其他耗時操作....
        //使用同步代碼塊對變量i進行同步操作,鎖對象為instance
        synchronized(instance){
            for(int j=0;j<10000;j++){
                i++;
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Thread t1=new Thread(instance);
        Thread t2=new Thread(instance);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(i);
    }
}

結果:

這里寫圖片描述

分析:將synchronized作用於一個給定的實例對象instance,即當前實例對象就是鎖對象,每次當線程進入synchronized包裹的代碼塊時就會要求當前線程持有instance實例對象鎖,如果當前有其他線程正持有該對象鎖,那么新到的線程就必須等待,這樣也就保證了每次只有一個線程執行i++;操作。當然除了instance作為對象外,我們還可以使用this對象(代表當前實例)或者當前類的class對象作為鎖,如下代碼:

//this,當前實例對象鎖
synchronized(this){
    for(int j=0;j<1000000;j++){
        i++;
    }
}

//class對象鎖
synchronized(AccountingSync.class){
    for(int j=0;j<1000000;j++){
        i++;
    }
}

結語

以上就是我對Synchronized的理解,希望能幫大家搞懂Synchronized,如果有什么錯誤還望大家多多包涵,多多指教哈,謝謝~

參考:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM