Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 多執行緒(三):synchronized、互斥與死鎖

編輯:Android 開發教學

為什麼需要同步

先看一段程式碼:

package com.maso.test;

public class ThreadTest2 implements Runnable {
    private TestObj testObj = new TestObj();

    public static void main(String[] args) {
        ThreadTest2 tt = new ThreadTest2();
        Thread t1 = new Thread(tt, "thread_1");
        Thread t2 = new Thread(tt, "thread_2");
        t1.start();
        t2.start();
    }

    @Override
    public void run() {
        for (int j = 0; j < 10; j++) {
            int i = fix(1);
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " : i = " + i);
        }
    }

    public int fix(int y) {
        return testObj.fix(y);
    }

    public class TestObj {
        int x = 10;

        public int fix(int y) {
            return x = x - y;
        }
    }
}

執行後會發現 x 被兩個執行緒同時讀寫,出現跳號、重複值甚至負數亂跳的情況。原因是 x = x - y 並不是不可分割的單一操作,它至少包含「讀取 x」、「相減」、「寫回 x」三步,而 thread_1 與 thread_2 共用同一個 TestObj 實例,交錯執行時就會互相踩到。

加上 synchronized

在呼叫端加上同步關鍵字:

public synchronized int fix(int y) {
    return testObj.fix(y);
}

此時輸出會變成從 9 一路遞減到 -10 的有序結果,不再錯亂。

加在另一個位置行不行

如果把 synchronized 加到 TestObj 類別自己的 fix 方法上:

public class TestObj {
    int x = 10;

    public synchronized int fix(int y) {
        return x = x - y;
    }
}

同樣可以達到目的,而且更合理——因為被保護的資料 x 屬於 TestObj,把鎖放在資料擁有者身上,語意比在外部呼叫端加鎖清楚得多。

把 synchronized 加在實例方法上,等價於:

synchronized (this) {
}

也就是以該物件本身作為鎖。若方法宣告為 static,synchronized 鎖的則是該類別的 Class 物件,這兩者互不相等,混用時會出現「看起來有鎖但其實沒互斥」的情況,實務上要特別留意。

最後提醒:synchronized 只能保證同一把鎖之間的互斥,若在多個資源之間取得順序不一致(A 先鎖 1 再鎖 2,B 先鎖 2 再鎖 1),就會形成死鎖。解法是約定全域一致的加鎖順序,並盡量縮小同步區塊的範圍。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved