java線程同步

來源:互聯網
上載者:User

多線程同步的實現最終依賴鎖機制。我們可以想象某一共用資源是一間屋子,每個人都是一個線程。當A希望進入房間時,他必須獲得門鎖,一旦A獲得門鎖,他進去後就立刻將門鎖上,於是B,C,D...就不得不在門外等待,直到A釋放鎖出來後,B,C,D...中的某一人搶到了該鎖(具體搶法依賴於JVM的實現,可以先到先得,也可以隨機挑選),然後進屋又將門鎖上。這樣,任一時刻最多有一人在屋內(使用共用資源)。

Java語言規範內建了對多線程的支援。對於Java程式來說,每一個對象執行個體都有一把“鎖”,一旦某個線程獲得了該鎖,別的線程如果希望獲得該鎖,只能等待這個線程釋放鎖之後。獲得鎖的方法只有一個,就是synchronized關鍵字。例如:

public class SharedResource {
    private int count = 0;

    public int getCount() { return count; }

    public synchronized void setCount(int count) { this.count = count; }

}

同步方法public synchronized void setCount(int count) { this.count = count; } 事實上相當於:

public void setCount(int count) {
    synchronized(this) { // 在此獲得this鎖
         this.count = count;

    } // 在此釋放this鎖
}

紅色部分表示需要同步的程式碼片段,該地區為“危險地區”,如果兩個以上的線程同時執行,會引發衝突,因此,要更改SharedResource的內部狀態,必須先獲得SharedResource執行個體的鎖。

退出synchronized塊時,線程擁有的鎖自動釋放,於是,別的線程又可以擷取該鎖了。

為了提高效能,不一定要鎖定this,例如,SharedResource有兩個獨立變化的變數:

public class SharedResouce {
    private int a = 0;
    private int b = 0;

    public synchronized void setA(int a) { this.a = a; }

    public synchronized void setB(int b) { this.b = b; }
}

若同步整個方法,則setA()的時候無法setB(),setB()時無法setA()。為了提高效能,可以使用不同對象的鎖:

public class SharedResouce {
    private int a = 0;
    private int b = 0;
    private Object sync_a = new Object();
    private Object sync_b = new Object();

    public void setA(int a) {
        synchronized(sync_a) {
            this.a = a;
        }
    }

    public synchronized void setB(int b) {
        synchronized(sync_b) {
            this.b = b;
        }
    }
}

聯繫我們

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