字節(jié)跳動面試官:i++ 是線程安全的嗎?
點擊“開發(fā)者技術前線”,選擇“星標”
在看|星標|留言,? 真愛

轉(zhuǎn)自:zemliu
鏈接:cnblogs.com/zemliu/p/3298685.html
背景
最近去面字節(jié)跳動,除了算法之外,問到了一個基礎題,關于i++ 是否線程安全?今天分享給大家。
簡介
volatile關鍵字保證了在多線程環(huán)境下,被修飾的變量在別修改后會馬上同步到主存,這樣該線程對這個變量的修改就是對所有其他線程可見的,其他線程能夠馬上讀到這個修改后值.
Thread的本地內(nèi)存
每個Thread都擁有自己的線程存儲空間 Thread何時同步本地存儲空間的數(shù)據(jù)到主存是不確定的
例子

借用Google JEREMY MANSON 的解釋,上圖表示兩個線程并發(fā)執(zhí)行,而且代碼順序上為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不可優(yōu)化volatile變量,如JVM優(yōu)化后變量讀取會使用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,原因是單線程執(zhí)行不會有線程安全問題// 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: -460370604Duration: 67.37s
原因是i++和++i并非原子操作,我們?nèi)舨榭醋止?jié)碼,會發(fā)現(xiàn)
void?f1()?{?i++;?}
的字節(jié)碼如下
void f1();Code:0: aload_01: dup2: getfield #2; //Field i:I5: iconst_16: iadd7: putfield #2; //Field i:I10: return
可見i++執(zhí)行了多部操作, 從變量i中讀取讀取i的值 -> 值+1 -> 將+1后的值寫回i中,這樣在多線程的時候執(zhí)行情況就類似如下了
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 包來提供線程安全的基本類型包裝類,例子如下
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,原因是單線程執(zhí)行不會有線程安全問題// 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: 0Duration: 105.15
結論
volatile解決了線程間共享變量的可見性問題 使用volatile會增加性能開銷 volatile并不能解決線程同步問題 解決i++或者++i這樣的線程同步問題需要使用synchronized或者AtomicXX系列的包裝類,同時也會增加性能開銷
最后福利:
在這里,我為大家準備了一份2020年最新最全的面試題及答案,這套電子書涵蓋了諸多后端,客戶端,前端技術棧的面試題和答案,相信可以幫助大家在最短的時間內(nèi)復習的大多數(shù)面試題,從而拿到自己心儀的offer。
前線推出學習交流群,加群一定要備注:
研究/工作方向+地點+學校/公司+昵稱(如java+上海+上交+可可)根據(jù)格式備注,可更快被通過且邀請進群,領取一份專屬學習禮包
掃碼加我微信進群,大廠內(nèi)推和技術交流,大佬們零距離



