1.解決的問題
解決多線程數據共享及同步
2.使用方式
2.1修飾實例方法
作用于當前實例幔睬,進入同步代碼需要獲取當前實例的鎖
synchronized void addA(){
a+=1;
}
等價于
void addA() {
synchronized (this) {
a += 1;
}
}
2.2 修飾靜態(tài)方法
作用于當前類雏亚,進入同步代碼需要獲取當前類的鎖
static synchronized void addA(){
a+=1;
}
等價于
void addA() {
synchronized (當前類.class) {
a += 1;
}
}
2.3 修飾代碼塊
作用于鎖對象惰赋,進入同步代碼需要獲取當前鎖對象的鎖
void addA(){
synchronized (object){
a+=1;
}
}
3.驗證
3.1 修飾實例方法/代碼塊 this
public class AccountingStaticSync implements Runnable {
static int a;
private String threadName;
synchronized void addA() {
a += 1;
}
/**
* synchronized 修飾實例方法等同于 synchronized (this)
*/
// void addA(){
// synchronized (this) {
// a += 1;
// }
// }
public void run() {
for (int index = 0; index < 100000; index++) {
addA();
Thread.yield();
}
}
public AccountingStaticSync(String threadName) {
this.threadName = threadName;
}
public static void main(String[] args) throws Exception {
int threadCount = 15;
List<Thread> threads = new LinkedList<Thread>();
for (int index = 0; index < threadCount; index++) {
threads.add(new Thread(new AccountingStaticSync(String.valueOf(index))));
}
for (int index = 0; index < threadCount; index++) {
threads.get(index).start();
}
for (int index = 0; index < threadCount; index++) {
threads.get(index).join();
}
System.out.println("a=" + a);
}
}
當多個線程以該方式修改共享數據時,導致數據不一致的發(fā)生
3.2 修飾靜態(tài)方法/共享對象
public class AccountingStaticSync implements Runnable {
static AccountingStaticSync sync = new AccountingStaticSync("sync");
static int a;
private String threadName;
static synchronized void addA() {
a += 1;
}
/**
* synchronized 修飾靜態(tài)方法等同于 synchronized (this.class) 或 synchronized (sync object)
*/
// void addA(){
// synchronized (AccountingStaticSync.class) {
// a += 1;
// }
// }
//
// void addA(){
// synchronized (sync) {
// a += 1;
// }
// }
public void run() {
for (int index = 0; index < 100000; index++) {
addA();
Thread.yield();
}
}
public AccountingStaticSync(String threadName) {
this.threadName = threadName;
}
public static void main(String[] args) throws Exception {
int threadCount = 15;
List<Thread> threads = new LinkedList<Thread>();
for (int index = 0; index < threadCount; index++) {
threads.add(new Thread(new AccountingStaticSync(String.valueOf(index))));
}
for (int index = 0; index < threadCount; index++) {
threads.get(index).start();
}
for (int index = 0; index < threadCount; index++) {
threads.get(index).join();
}
System.out.println("a=" + a);
}
}
修飾靜態(tài)方法/this.class/sync object 均是阻塞在同一個對象上坪郭,因此可以安全地執(zhí)行
4.底層原理
4.1 同步對象
當synchronized修飾實例方法/對象時赊颠,是基于對象頭以及monitorenter 和 monitorexit 指令來實現同步的
4.1.1 對象頭
實例變量:存放類的屬性數據信息,包括父類的屬性信息瑰剃,如果是數組的實例部分還包括數組的長度齿诉,這部分內存按4字節(jié)對齊
填充數據:由于虛擬機要求對象起始地址必須是8字節(jié)的整數倍。填充數據不是必須存在的晌姚,僅僅是為了字節(jié)對齊粤剧,這點了解即可
4.1.2MarkWord
虛擬機位數 | 頭對象結構 | 說明 |
---|---|---|
32/64bit | Mark Word | 存儲對象的hashCode、鎖信息或分代年齡或GC標志等信息 |
32/64bit | Class Metadata Address | 類型指針指向對象的類元數據挥唠,JVM通過這個指針確定該對象是哪個類的實例 |
其中Mark Word在默認情況下存儲著對象的HashCode抵恋、分代年齡、鎖標記位等以下是32位JVM的Mark Word默認存儲結構
鎖狀態(tài) | 25bit | 4bit | 1bit是否偏向鎖 | 2bit鎖標志位 |
---|---|---|---|---|
無鎖狀態(tài) | 對象hashcode | 對象分代年齡 | 0 | 01 |
由于對象頭的信息是與對象自身定義的數據沒有關系的額外存儲成本宝磨,因此考慮到JVM的空間效率弧关,Mark Word 被設計成為一個非固定的數據結構,以便存儲更多有效的數據唤锉,它會根據對象本身的狀態(tài)復用自己的存儲空間世囊,如32位JVM下,
除了上述列出的Mark Word默認存儲結構外窿祥,還有如下可能變化的結構:
4.1.3 重量鎖---synchronized
重量鎖中的指針指向一個 monitor 對象株憾,該 monitor伴隨鎖對象生成和銷毀
monitor 的數據結構如下
_ownerObjectMonitor() {
_header = NULL;
_count = 0; //記錄鎖個數,重入時晒衩,_count + 1, 釋放時 _count - 1
_waiters = 0,
_recursions = 0;
_object = NULL;
_owner = NULL; //記錄持有鎖的線程嗤瞎,因此是可重入的
_WaitSet = NULL; // 處于wait狀態(tài)的線程墙歪,會被加入到_WaitSet
_WaitSetLock = 0 ;
_Responsible = NULL ;
_succ = NULL ;
_cxq = NULL ;
FreeNext = NULL ;
_EntryList = NULL ; //處于等待鎖block狀態(tài)的線程,會被加入到該列表
_SpinFreq = 0 ;
_SpinClock = 0 ;
OwnerIsThread = 0 ;
}
- ObjectMonitor中有兩個隊列猫胁,_WaitSet 和 _EntryList箱亿,用來保存ObjectWaiter對象列表( 每個等待鎖的線程都會被封裝成ObjectWaiter對象)
- _owner指向持有ObjectMonitor對象的線程,當多個線程同時訪問一段同步代碼時弃秆,首先會進入 _EntryList 集合
- 當線程獲取到對象的monitor 后進入 _Owner 區(qū)域并把monitor中的owner變量設置為當前線程同時monitor中的計數器count加1
- 若線程調用 wait() 方法届惋,將釋放當前持有的monitor,owner變量恢復為null菠赚,count自減1,同時該線程進入 WaitSet集合中等待被喚醒脑豹。若當前線程執(zhí)行完畢也將釋放monitor(鎖)并復位變量的值,以便其他線程進入獲取monitor(鎖)
- 無論執(zhí)行代碼的過程中成功或異常衡查,均會釋放鎖
4.2同步方法
靜態(tài)同步方法調用指令讀取運行時常量池中方法的 ACC_SYNCHRONIZED 標志來隱式實現的
- 方法級的同步是隱式瘩欺,即無需通過字節(jié)碼指令來控制的,它實現在方法調用和返回操作之中
- JVM可以從方法常量池中的方法表結構(method_info Structure) 中的 ACC_SYNCHRONIZED 訪問標志區(qū)分一個方法是否同步方法
- 當方法調用時拌牲,調用指令將會 檢查方法的 ACC_SYNCHRONIZED 訪問標志是否被設置俱饿,如果設置了,執(zhí)行線程將先持有monitor(虛擬機規(guī)范中用的是管程一詞)塌忽, 然后再執(zhí)行方法
- 最后再方法完成(無論是正常完成還是非正常完成)時釋放monitor
- 無論執(zhí)行代碼的過程中成功或異常拍埠,均會釋放鎖