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

Android 多線程研究(三):線程同步、互斥與死鎖

編輯:關於 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 被兩個線程同時操作,很容易導致錯誤結果。要解決這個問題,可以加上 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;
    }
}

把 synchronized 加到方法上,等價於:

synchronized(this) { }

此時兩個線程用的是同一個 TestObj 實例,確實實現了同步,但輸出結果並不理想。這是因為 A 線程執行完 x = x - y 後還沒輸出,B 線程就已經進來開始執行 x = x - y 了。所以像下面這樣把輸出也放進同步塊裡,就不會有問題:

public class TestObj {
    public TestObj() { System.out.println("調用了構造函數"); }
    int x = 10;
    public synchronized int fix(int y) {
        x = x - y;
        System.out.println(Thread.currentThread().getName() + " : x = " + x);
        return x;
    }
}

如果外部的 fix 方法改成這樣:

public int fix(int y) {
    ax++;
    if (ax % 2 == 0) {
        return testObj.fix(y, testObj.str1);
    } else {
        return testObj.fix(y, testObj.str2);
    }
}
public class TestObj {
    String str1 = "a1";
    String str2 = "a2";
    public int fix(int y, String str) {
        synchronized (str) {
            x = x - y;
            System.out.println(Thread.currentThread().getName() + " : x = " + x);
        }
        return x;
    }
}

此時 synchronized 裡的 str 對象並不是同一個,兩個線程持有的對象鎖不同,自然無法實現同步。由此可見,要實現線程之間的互斥,必須使用同一個對象鎖。

什麼是死鎖?

打個比方:你和同學合租了一套兩居室,你拿著你房間的鑰匙,同學拿著他房間的鑰匙。現在你在自己房間等他把鑰匙給你、好進他房間;而他也在自己房間等著你把鑰匙給他、好進你房間。兩個人互相等待對方先交出鑰匙,誰也進不去——這就是死鎖。

package com.maso.test;
public class ThreadDieSock implements Runnable {
    private int flag = 1;
    private Object obj1 = new Object(), obj2 = new Object();
    public void run() {
        System.out.println("flag=" + flag);
        if (flag == 1) {
            synchronized (obj1) {
                System.out.println("我已經鎖定obj1,休息0.5秒後鎖定obj2去!");
                try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }
                synchronized (obj2) {
                    System.out.println("1");
                }
            }
        }
        if (flag == 0) {
            synchronized (obj2) {
                System.out.println("我已經鎖定obj2,休息0.5秒後鎖定obj1去!");
                try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }
                synchronized (obj1) {
                    System.out.println("0");
                }
            }
        }
    }
    public static void main(String[] args) {
        ThreadDieSock run01 = new ThreadDieSock();
        ThreadDieSock run02 = new ThreadDieSock();
        run01.flag = 1;
        run02.flag = 0;
        Thread thread01 = new Thread(run01);
        Thread thread02 = new Thread(run02);
        System.out.println("線程開始嘍!");
        thread01.start();
        thread02.start();
    }
}

在上面的例子中,一個線程先鎖 obj1 再鎖 obj2,另一個線程先鎖 obj2 再鎖 obj1,加鎖順序相反,於是雙方互相等待對方釋放鎖,最終陷入死鎖。這也提醒我們:在實際開發中,盡量保持一致的加鎖順序,是避免死鎖的有效手段之一。

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