圖解Java多執行緒

李西北發表於2017-10-27

zqhxuyuan.github.io/2017/10/25/…

圖解Java多執行緒筆記:tutorials.jenkov.com/java-concur…
Java記憶體模型(JMM)定義了:how and when different threads can see
values written to shared variables by other threads,
and how to synchronize access to shared variables when necessary.
1
Java堆和棧中的物件儲存位置:
2
Java記憶體模型與硬體模型:
3
執行緒讀取主記憶體的資料到CPU緩衝中,當資料放在不同位置時,會有兩個問題:可見性與靜態條件
4
A synchronized block in Java is synchronized on some object.
All synchronized blocks synchronized on the same object can only
have one thread executing inside them at the same time.
All other threads attempting to enter the synchronized block are blocked
until the thread inside the synchronized block exits the block.
The synchronized keyword can be used to mark four different types of blocks:
Instance methods -> on the instance (object) owning the method
Static methods -> on the class object of the class belongs to …
Code blocks inside instance methods
Code blocks inside static methods
Synchronized Instance methods(例項方法的同步):
5
靜態方法的同步:
6
程式碼塊的同步:
7
用jstack檢視,同一個監視器物件只允許有一個執行緒訪問:
d
例項方法的同步加上程式碼塊this的同步,仍然針對同一個例項物件:
e
自定義監視器物件:
f
同一個例項物件的加鎖:
g
不同例項物件的加鎖:
17
Volatile keyword guarantees visibility of changes to variables across threads.
every read of a volatile variable will be
read from the computer’s main memory,
and not from the CPU cache.
every write to a volatile variable will be
written to main memory,
and not just to the CPU cache.
If Thread A writes to a volatile variable and Thread B subsequently reads the same volatile variable, then all variables visible to Thread A before writing the volatile variable, will also be visible to Thread B after it has read the volatile variable.
The reading and writing instructions of volatile variables cannot be reordered by the JVM. Instructions before and after can be reordered, but the volatile read or write cannot be mixed with these instructions. Whatever instructions follow a read or write of a volatile variable are guaranteed to happen after the read or write.
volatile變數不保證事務:
56
volatile變數仍然會存在競態條件:
27
volatile變數會禁止重排序:
49
如果變數在volatile變數更新之後,不保證寫到主存:
11
為了保證可見性,不需要為每個變數都定義為volatile型別:
36
volatile變數是個記憶體屏障,在這之前和之後的指令可以重排序:
56
本地執行緒的示例:
15
下面的上圖沒有使用本地執行緒,下圖使用了本地執行緒:
29
執行緒的訊號量實現方式–busy waiting:
53
或者可以用volatile變數:
16
wait和notify的示例:
34
notify與notifyAll的示例:
51
等待執行緒有可能意外被喚醒,需要用while迴圈繼續判斷是否被喚醒執行緒notify:
05
一次喚醒所有執行緒,或者每次一個個地喚醒:
21
不同執行緒之間採用字串作為監視器鎖,會喚醒別的執行緒:
43
不同執行緒之間的訊號沒有共享,等待執行緒被喚醒後繼續進入wait狀態:
03
不同執行緒的等待與喚醒示例:
18

相關文章