從頭認識java-17.4 詳解同步(4)-同步阻塞、synchronized和volatile

來源:互聯網
上載者:User

從頭認識java-17.4 詳解同步(4)-同步阻塞、synchronized和volatile

這一章節我們來介紹同步阻塞、synchronized和volatile。

1.同步阻塞

之前我們提到過synchronized放在同步方法上:

public synchronized void transfer(int fromAccount, int toAccount,double money) {if (accounts[fromAccount] < money) {return;}accounts[fromAccount] -= money;System.out.printf("從" + fromAccount + "賬戶轉出%10.2f元,", money);accounts[toAccount] += money;System.out.printf("從" + toAccount + "賬戶轉入%10.2f元,", money);System.out.printf("總數:%10.2f元", getTotal());System.out.println();}


其實他的等價代碼是這樣的:

private Object lock = new Object();public void transfer(int fromAccount, int toAccount, double money) {synchronized (lock) {if (accounts[fromAccount] < money) {return;}accounts[fromAccount] -= money;System.out.printf("從" + fromAccount + "賬戶轉出%10.2f元,", money);accounts[toAccount] += money;System.out.printf("從" + toAccount + "賬戶轉入%10.2f元,", money);System.out.printf("總數:%10.2f元", getTotal());System.out.println();}}


上面的lock扮演的就是我們平常所說的那把鎖,只有持有這把鎖,線程才能進入方法進行操作,而synchronized就是控制這把鎖一次只能給一個線程持有,從而實現同步阻塞。

 

2. volatile

volatile是另一種實現線程阻塞的方法,但是他具有局限性:就是只完成變數賦值,而不執行其他動作。

可行的方式:

package com.ray.ch17;public class Test {private volatile boolean isDone;public boolean isDone() {return isDone;}public void setDone(boolean isDone) {this.isDone = isDone;}}

等價代碼:

package com.ray.ch17;public class Test {private boolean isDone;public synchronized boolean isDone() {return isDone;}public synchronized void setDone(boolean isDone) {this.isDone = isDone;}}


不可行的方式:

package com.ray.ch17;public class Test {private volatile boolean isDone;public void flipDone() {isDone = !isDone;}}



總結:這一章節主要介紹同步阻塞和volatile的使用方式。 

聯繫我們

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