Java 多線程(五)之 synchronized 的使用

來源:互聯網
上載者:User

標籤:為我   沒有   rgs   方式   講解   lis   同步   添加   trace   

並發編程為我們帶來了很多便利, 但同時也帶來了安全執行緒問題。

安全執行緒

執行緒安全性的定義:

當多個線程訪問某一個類時, 這個類始終能表示出正確的行為, 那麼就稱這個類是安全執行緒的。

其產生的原因可以歸結如下:

1.共用資料: 只有共用的資料才會產生帶來安全性問題。 如果是方法內部聲明的變數, 其是在虛擬機器棧中, 為每個線程獨享, 不存在安全性問題。

2.多個線程對共用資料進行同時操作。多線程對同一共用資料進行同時性的操作,此時共用資料就會影響到彼此。

由安全執行緒引起的問題, 在此做一個樣本:

public class UnsafeThread implements Runnable {    private static int count = 0;    public void increase(){        count++;    }    public void run() {        for (int i = 0; i < 2000000; i++) {            increase();        }    }    public static void main(String[] args) {        UnsafeThread myThread = new UnsafeThread();        Thread thread1 = new Thread(myThread);        Thread thread2 = new Thread(myThread);        thread1.start();        thread2.start();        try {            thread1.join();            thread2.join();            System.out.println(count);        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

執行後, 兩個線程, 每個線程對 count 進行了 2000000 次自增, 預期的結果應該是 4000000, 然而, 執行後發現結果基本上都不是對的, 每次不一樣, 但都比 4000000 小。為什嗎?

i++ 的步驟, 應該是:

讀->改->寫

但是, 如果在一個線程讀的時候, 還沒寫回去, 另一個線程也讀了,那麼就是有一次操作相當於沒有效, 導致最後的結果就會比預期的少了。

互斥鎖

因此, 為瞭解決該這些問題, 我們想到的對策:

  1. 消除共用資料: 想法很好, 但有些情況下想要完全的消除是不可能的, 我們只可能儘可能的減少共用資料。
  2. 限定同一時刻, 只有一個線程能對共用資料進行操作, 其他線程需要等到該線程處理完之後再進行操作。

互斥鎖就可以解決這類問題。

互斥鎖的特點

  1. 線程在進入同步代碼塊之前會自動擷取鎖,並且在退出同步代碼塊時會自動釋放鎖。
  2. 在同一時刻, 只有一個線程能持有這個鎖。當線程 A 嘗試擷取一個由線程 B 持有的鎖時, 線程 A 必須等待或阻塞, 直到線程 B 釋放了這個鎖。 如果 B 不釋放這個鎖, 則 A 就需要一直等待。
  3. 可重新進入性: 指的是同一線程 外層函數獲得鎖之後 ,內層遞迴函式仍然有擷取該鎖的代碼,但不受影響。
內建鎖 synchronized

在本文章, 我們來討論 Java 所提供的一種內建的互斥鎖, 使用 synchronized 來修飾:

 synchronized(lock){    // 訪問或修改共用資料 }

對剛剛的問題, 我們只需要加一個關鍵字即可

public synchronized void increase(){    count++;}

最後的輸出結果, 必然是 4000000。

由 synchronized 修飾的代碼塊以原子方式(一組語句組成一個不可分割的單元)執行。 任何執行同步代碼塊的線程, 都看不到其他線程正在執行的由同一個鎖保護的同步代碼塊。

synchronized 的使用有如下三種方式:

  1. 普通同步方法,鎖是當前執行個體對象(this);
  2. 靜態同步方法,鎖是當前類的 Class 對象;
  3. 同步代碼塊,鎖是括弧裡面的對象。
普通同步方法,鎖是當前執行個體對象(this)

普通同步方法, 鎖的是當前的 this 對象, 在以上的代碼中, 我們驗證了互斥的效果。

驗證普通方法中的鎖的對象是同一個。

如果兩個函數 increase 和 decrease 是同一對象中的普通函數,都使用 synchronized。 則一個函數正在運行時, 鎖已經被一個線程所獲得,如果另一個線程 相要進入另一個函數就進不去了。

public class MyThread implements Runnable {    private int state=0;    private static int count = 0;    public synchronized void increase(){        System.out.println(System.currentTimeMillis()+" increase begin");        try {            Thread.sleep(5000L);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println(System.currentTimeMillis()+" increase end");    }    public synchronized void decrease(){        System.out.println(System.currentTimeMillis()+" decrease begin");        try {            Thread.sleep(10000L);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println(System.currentTimeMillis()+" decrease end");    }    public void run() {        if (state == 0) {            state = 1;            increase();        }else{            state = 0;            decrease();        }    }    public static void main(String[] args) {        MyThread myThread = new MyThread();        Thread thread1 = new Thread(myThread);        Thread thread2 = new Thread(myThread);        thread1.start();        thread2.start();        try {            thread1.join();            thread2.join();            System.out.println(count);        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

該段代碼運行後結果如下:

1535644833489 increase begin1535644838489 increase end1535644838489 decrease begin1535644848489 decrease end

在 thread1 運行時,其啟動的是 increase 函數, 函數內部暫停了 5000 毫秒, 在此期間, thread2 已經啟動, 但卻需要等待 increase 結束後才能進入 decrease 函數。

驗證不同的對象普通方法的鎖不一樣

如果對象不一樣, 則鎖不一樣, 起不到作用。

在剛剛結果出現錯誤的線程中, 給 UnsafeThread 加上 synchronized , 並改變 main 函數來驗證這個結果。

public static void main(String[] args) {    UnsafeThread unsafeThread = new UnsafeThread();    UnsafeThread unsafeThread2 = new UnsafeThread();    Thread thread1 = new Thread(unsafeThread);    Thread thread2 = new Thread(unsafeThread2);    thread1.start();    thread2.start();    try {        thread1.join();        thread2.join();        System.out.println(count);    } catch (InterruptedException e) {        e.printStackTrace();    }}

輸出結果也會是比 4000000 小的數字, 因為 count 是 static 修飾的, 是一個全域變數, 哪怕是兩個不同的對象操作的也是同一個變數。而由於 unsafeThread 和 unsafeThread2 是兩個不同的對象, 因此 synchronized 鎖的對象就不一樣, 鎖不一樣就起不到互斥的效果。

因為鎖的是當前的對象, 因此如果兩個線程所持有的對象如果不一樣, 則不會起到互斥的作用

靜態同步方法,鎖是當前類的class對象

如果 synchronized 作用在靜態方法上, 鎖的是當前的 Class 進行加鎖。因為靜態成員不屬於具體的某一個對象, 因此顯然繼續使用 this 作為鎖是不可行的。

驗證同類的static 方法之間, 鎖是同一個鎖。

首先, 定義兩個線程類

public class ThreadA implements Runnable {    private ThreadStaticTest threadStaticTest;    public ThreadA(ThreadStaticTest threadStaticTest) {        this.threadStaticTest = threadStaticTest;    }    public void run() {        threadStaticTest.staticMethodA();    }}
public class ThreadB implements Runnable {    private ThreadStaticTest threadStaticTest;    public ThreadB(ThreadStaticTest threadStaticTest) {        this.threadStaticTest = threadStaticTest;    }    public void run() {        threadStaticTest.staticMethodB();    }}

然後, 定義一個測試類別

public class ThreadStaticTest {    public synchronized static void staticMethodA() {        System.out.println(Thread.currentThread().getName() + " staticMethodA in "            + System.currentTimeMillis());        try {            Thread.sleep(2000L);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println(Thread.currentThread().getName() + " staticMethodA out "             + System.currentTimeMillis());    }    public synchronized static void staticMethodB() {        System.out.println(Thread.currentThread().getName() + " staticMethodB in "             + System.currentTimeMillis());        try {            Thread.sleep(3000L);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println(Thread.currentThread().getName() + " staticMethodB out "             + System.currentTimeMillis());    }    public static void main(String[] args) {        ThreadStaticTest threadStaticTest = new ThreadStaticTest();        Thread ta = new Thread(new ThreadA(threadStaticTest));        Thread tb = new Thread(new ThreadB(threadStaticTest));        ta.setName("ThreadA");        tb.setName("ThreadB");        ta.start();        tb.start();        try {            ta.join();            tb.join();        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

運行後的結果如下:

ThreadA staticMethodA in 1535769147351ThreadA staticMethodA out 1535769149351ThreadB staticMethodB in 1535769149351ThreadB staticMethodB out 1535769152351

結果上看,沒什麼不同。 但其本質上, 鎖的對象還是不一樣的, synchronized 關鍵字加到靜態方法上, 鎖的是 Class 類, 而加到非靜態方法上, 鎖的是 this對象。

驗證同一個類的 static 方法和普通方法鎖不同

首先,在之前的 ThreadStaticTest 類內部加上普通方法

public synchronized void methodC() {    System.out.println(Thread.currentThread().getName() + " methodC in "            + System.currentTimeMillis());    try {        Thread.sleep(3000L);    } catch (InterruptedException e) {        e.printStackTrace();    }    System.out.println(Thread.currentThread().getName() + " methodC out "            + System.currentTimeMillis());}

定義新的線程類

public class ThreadC implements Runnable {    private ThreadStaticTest threadStaticTest;    public ThreadC(ThreadStaticTest threadStaticTest) {        this.threadStaticTest = threadStaticTest;    }    public void run() {        threadStaticTest.methodC();    }}

最後在 main 函數中添加新的調用

public static void main(String[] args) {    ThreadStaticTest threadStaticTest = new ThreadStaticTest();    Thread ta = new Thread(new ThreadA(threadStaticTest));    Thread tb = new Thread(new ThreadB(threadStaticTest));    Thread tc = new Thread(new ThreadC(threadStaticTest));    ta.setName("ThreadA");    tb.setName("ThreadB");    tc.setName("ThreadC");    ta.start();    tb.start();    tc.start();    try {        ta.join();        tb.join();        tc.join();    } catch (InterruptedException e) {        e.printStackTrace();    }}

最後結果如下

ThreadA staticMethodA in 1535769547612ThreadC methodC in 1535769547612ThreadA staticMethodA out 1535769549612ThreadB staticMethodB in 1535769549612ThreadC methodC out 1535769550612ThreadB staticMethodB out 1535769552612

可以看到, 名為 ThreadC 的線程“亂入”, 而線程 ThreadA 和 ThreadB 還是一個結束後一個在進入。證明 ThreadA 和 ThreadB 持有的是同一個鎖。

同步代碼塊,鎖是括弧裡面的對象

在方法(靜態或普通)上使用 synchronized , 隨之而帶來的就是效能上的降低, 在前面我們證明了, 如果同一對象的多個普通方法使用了 synchronized ,他們之間會相互阻塞的, 因為持有同樣的鎖 。所以, 最好只在並發情景中需要修改共用資料的方法上使用它。

那麼, 我們怎麼來做呢?可能有時候我們編寫的方法很龐大, 但其中只有一小塊是操作共用資料的, 這時候在方法上加 synchronized 顯然是不划算的, 同步代碼塊就可以解決此類的問題。

 synchronized(lock){    // 訪問或修改共用資料 }

在同步代碼塊中, synchronized 後面括弧中的 lock 可以是任意對象。

前面的普通方法, 對應的是

 synchronized(this){    // 訪問或修改共用資料 }

靜態方法對應的是

    // XXX 對應的是相應的類名 synchronized(XXX.class){    // 訪問或修改共用資料 }

而使用了同步代碼塊之後, 我們可以一定程度上減少效能的降低。 如果有兩個變數, 對應方法 methodA 和 methodB 進行修改, 如果使用兩個不同的 lockA 和 lockB 對他們進行加鎖,則操作時不會相互阻塞。

首先, 定義測試類別

public class SynBlock {    private Lock lockA = new Lock();    private Lock lockB = new Lock();    private static int countA = 0;    private static int countB = 0;    public void methodA() {        synchronized (lockA) {            try {                System.out.println(Thread.currentThread().getName() + " methodA begin "                        + System.currentTimeMillis());                for (int i = 0; i < 2000000; i++) {                    countA++;                }                Thread.sleep(1000L);                System.out.println(Thread.currentThread().getName() + " methodA end "                        + System.currentTimeMillis());            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }    public void methodB() {        synchronized (lockB) {            try {                System.out.println(Thread.currentThread().getName() + " methodA begin "                        + System.currentTimeMillis());                for (int i = 0; i < 1000000; i++) {                    countB++;                }                Thread.sleep(2000L);                System.out.println(Thread.currentThread().getName() + " methodA end "                        + System.currentTimeMillis());            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }    class Lock {    }    public static void main(String[] args) {        SynBlock synBlock = new SynBlock();        Thread threadA = new Thread(new SynBlockThreadA(synBlock));        Thread threadB = new Thread(new SynBlockThreadB(synBlock));        threadA.setName("ThreadA");        threadB.setName("ThreadB");        threadA.start();        threadB.start();        try {            threadA.join();            threadB.join();            System.out.println("countA=" + countA);            System.out.println("countB=" + countB);        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

對應的線程類

public class SynBlockThreadA implements Runnable {    private SynBlock synBlock;    public SynBlockThreadA(SynBlock synBlock) {        this.synBlock = synBlock;    }    public void run() {        synBlock.methodA();    }}
public class SynBlockThreadB implements Runnable {    private SynBlock synBlock;    public SynBlockThreadB(SynBlock synBlock) {        this.synBlock = synBlock;    }    public void run() {        synBlock.methodB();    }}

最後的輸出結果如下

ThreadA methodA begin 1535772725304ThreadB methodA begin 1535772725304ThreadA methodA end 1535772726319ThreadB methodA end 1535772727320countA=2000000countB=1000000

從結果可以看出 ThreadA 和 ThreadB 沒有互相阻塞。

但是, 而如果將 methodB 中的 lockB 改成 lockA, 則運行結果如下

ThreadA methodA begin 1535774917415ThreadA methodA end 1535774918431ThreadB methodA begin 1535774918431ThreadB methodA end 1535774920431countA=2000000countB=1000000

起到了互斥的效果。

因此, 同步代碼塊的如下:

在多個線程持有同一個lock(括弧內的對象相同),同一時間只有一個線程可以執行 synchronized 同步代碼塊中的代碼。

synchronized 的使用到此暫時就結束, 後續會進行其原理的深入講解和結合鎖進行更深入的使用講解。

Java 多線程(五)之 synchronized 的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.