从 volatile 说到 i++ 的线程安全问题
點擊上方?好好學java?,選擇?星標?公眾號
來源:cnblogs.com/zemliu/p/3298685.html
簡介
volatile關鍵字保證了在多線程環境下,被修飾的變量在別修改后會馬上同步到主存,這樣該線程對這個變量的修改就是對所有其他線程可見的,其他線程能夠馬上讀到這個修改后值.
Thread的本地內存
每個Thread都擁有自己的線程存儲空間
Thread何時同步本地存儲空間的數據到主存是不確定的
借用Google JEREMY MANSON 的解釋,上圖表示兩個線程并發執行,而且代碼順序上為Thread1->Thread2
1、不用 volatile
假如ready字段不使用volatile,那么Thread 1對ready做出的修改對于Thread2來說未必是可見的,是否可見是不確定的.假如此時thread1 ready泄露了(leak through)了,那么Thread 2可以看見ready為true,但是有可能answer的改變并沒有泄露,則thread2有可能會輸出 0 (answer=42對thread2并不可見)
2、使用 volatile
使用volatile以后,做了如下事情
每次修改volatile變量都會同步到主存中
每次讀取volatile變量的值都強制從主存讀取最新的值(強制JVM不可優化volatile變量,如JVM優化后變量讀取會使用cpu緩存而不從主存中讀取)
線程 A 中寫入 volatile 變量之前可見的變量, 在線程 B 中讀取該 volatile 變量以后, 線程 B 對其他在 A 中的可見變量也可見. 換句話說, 寫 volatile 類似于退出同步塊, 而讀取 volatile 類似于進入同步塊
所以如果使用了volatile,那么Thread2讀取到的值為read=>true,answer=>42,當然使用volatile的同時也會增加性能開銷
注意
volatile并不能保證非源自性操作的多線程安全問題得到解決,volatile解決的是多線程間共享變量的可見性問題,而例如多線程的i++,++i,依然還是會存在多線程問題,它是無法解決了.如下:使用一個線程i++,另一個i--,最終得到的結果不為0
public?class?VolatileTest?{private?static?volatile?int?count = 0;private?static?final int?times = Integer.MAX_VALUE;public?static?void?main(String[] args) {long?curTime = System.nanoTime();Thread decThread = new?DecThread();decThread.start();// 使用run()來運行結果為0,原因是單線程執行不會有線程安全問題// new DecThread().run();System.out.println("Start thread: "?+ Thread.currentThread() + " i++");for?(int?i = 0; i < times; i++) {count++;}System.out.println("End thread: "?+ Thread.currentThread() + " i--");// 等待decThread結束while?(decThread.isAlive());long?duration = System.nanoTime() - curTime;System.out.println("Result: "?+ count);System.out.format("Duration: %.2fs\n", duration / 1.0e9);}private?static?class?DecThread?extends?Thread?{@Overridepublic?void?run() {System.out.println("Start thread: "?+ Thread.currentThread() + " i--");for?(int?i = 0; i < times; i++) {count--;}System.out.println("End thread: "?+ Thread.currentThread() + " i--");}} }最后輸出的結果是
Start?thread: Thread[main,5,main] i++ Start?thread: Thread[Thread-0,5,main] i-- End?thread: Thread[main,5,main] i-- End?thread: Thread[Thread-0,5,main] i-- Result: -460370604 Duration: 67.37s原因是i++和++i并非原子操作,我們若查看字節碼,會發現
void?f1()?{ i++; }的字節碼如下
void f1(); Code: 0: aload_0 1: dup 2: getfield #2; //Field i:I 5: iconst_1 6: iadd 7: putfield #2; //Field i:I 10: return可見i++執行了多部操作, 從變量i中讀取讀取i的值 -> 值+1 -> 將+1后的值寫回i中,這樣在多線程的時候執行情況就類似如下了
Thread1?????????????Thread2 r1 = i; r3?= i; r2?= r1 + 1; r4?= r3 + 1; i?= r2; i?= r4;這樣會造成的問題就是 r1, r3讀到的值都是 0, 最后兩個線程都將 1 寫入 i, 最后 i 等于 1, 但是卻進行了兩次自增操作
可知加了volatile和沒加volatile都無法解決非原子操作的線程同步問題
線程同步問題的解決
Java提供了java.util.concurrent.atomic 包來提供線程安全的基本類型包裝類,例子如下
package?com.qunar.atomicinteger;import?java.util.concurrent.atomic.AtomicInteger;/*** @author?zhenwei.liu created on 2013 13-9-2 下午10:18* @version?$Id$*/ public?class?SafeTest?{private?static?AtomicInteger count = new?AtomicInteger(0);private?static?final?int?times = Integer.MAX_VALUE;public?static?void?main(String[] args)?{long?curTime = System.nanoTime();Thread decThread = new?DecThread();decThread.start();// 使用run()來運行結果為0,原因是單線程執行不會有線程安全問題// new DecThread().run();System.out.println("Start thread: "?+ Thread.currentThread() + " i++");for?(int?i = 0; i < times; i++) {count.incrementAndGet();}// 等待decThread結束while?(decThread.isAlive());long?duration = System.nanoTime() - curTime;System.out.println("Result: "?+ count);System.out.format("Duration: %.2f\n", duration / 1.0e9);}private?static?class?DecThread?extends?Thread?{@Overridepublic?void?run()?{System.out.println("Start thread: "?+ Thread.currentThread() + " i--");for?(int?i = 0; i < times; i++) {count.decrementAndGet();}System.out.println("End thread: "?+ Thread.currentThread() + " i--");}} }輸出
Start?thread: Thread[main,5,main] i++ Start?thread: Thread[Thread-0,5,main] i-- End?thread: Thread[Thread-0,5,main] i-- Result: 0 Duration: 105.15結論
volatile解決了線程間共享變量的可見性問題
使用volatile會增加性能開銷
volatile并不能解決線程同步問題
解決i++或者++i這樣的線程同步問題需要使用synchronized或者AtomicXX系列的包裝類,同時也會增加性能開銷
總結
以上是生活随笔為你收集整理的从 volatile 说到 i++ 的线程安全问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 再见 Maven,我用它!!!
- 下一篇: 卧槽!阿里云推出“网盘”,百度网盘迎来劲