java中volatile不能保證安全執行緒(執行個體講解)

來源:互聯網
上載者:User

標籤:指令碼   string   method   inter   article   結果   線程   rup   技術   

java中volatile不能保證安全執行緒(執行個體講解)

轉載  2017-09-04   Think-007    我要評論

下面小編就為大家帶來一篇java中volatile不能保證安全執行緒(執行個體講解)。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧今天打了打代碼研究了一下java的volatile關鍵字到底能不能保證安全執行緒,經過實踐,volatile是不能保證安全執行緒的,它只是保證了資料的可見度,不會再緩衝,每個線程都是從主存中讀到的資料,而不是從緩衝中讀取的資料,附上代碼如下,當synchronized去掉的時候,每個線程的結果是亂的,加上的時候結果才是正確的。?
1234567891011121314151617181920212223242526272829303132333435 /** *  * 類簡要描述 *  * <p> * 類詳細描述 * </p> *  * @author think *  */ public class VolatileThread implements Runnable {  private volatile int a = 0;  @Override public void run() {  // TODO Auto-generated method stub//  synchronized (this) {   a = a + 1;   System.out.println(Thread.currentThread().getName() + ":----" + a);   try {    Thread.sleep(100);    a = a + 2;   } catch (InterruptedException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }    System.out.println(Thread.currentThread().getName() + ":----" + a);//  } } }
?
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 /** *  * 類簡要描述 *  * <p> * 類詳細描述 * </p> *  * @author think *  */ public class VolatileMain {  public static void main(String[] args) {   VolatileThread s = new VolatileThread();   Thread t1 = new Thread(s);  Thread t2 = new Thread(s);  Thread t3 = new Thread(s);  Thread t4 = new Thread(s);  t1.start();  t2.start();  t3.start();  t4.start();      /*  同步的結果  Thread-2:----1  Thread-2:----3  Thread-0:----4  Thread-0:----6  Thread-3:----7  Thread-3:----9  Thread-1:----10  Thread-1:----12*/   /*    去掉同步的結果  Thread-0:----1  Thread-1:----2  Thread-2:----3  Thread-3:----4  Thread-0:----8  Thread-3:----10  Thread-1:----10  Thread-2:----12*/      } }

以上這篇java中volatile不能保證安全執行緒(執行個體講解)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援指令碼之家。

java中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.