publicstatic
void main(string args) throws
exception
};runnable run2 = new
runnable()
};runnable run3 = new
runnable()
};runnable run4 = new
runnable()
};newthread(run1).start();
// new thread(run2).start();
// new thread(run3).start();
// new thread(run4).start();
}public
static
void testcase(int
tid)
system.out.println("normal test" + tid + " "
+ (system.currenttimemillis() -start));
start =system.currenttimemillis();
for (int i = 0; i < n; i++)
system.out.println("synchronized test" + tid + " "
+ (system.currenttimemillis() -start));
}}public
static
void
testprocess()
if (i == 0)
}}public
static
void
ntestprocess()
public
static
synchronized
void
stestprocess()
注意上面加紅的**
結果如下:
normal test1 318synchronized test1 291
將加紅**注釋去掉乙個,結果如下:
normal test2 336normal test1 348synchronized test2 617
synchronized test1 631
加紅**注釋去掉兩個,結果如下:
normal test2 362normal test3 392
normal test1 399
synchronized test3 892
synchronized test2 936
synchronized test1 935
加紅**注釋全部去掉,結果如下:
normal test2 416normal test4 420
normal test1 427
normal test3 436
synchronized test3 992
synchronized test2 1077
synchronized test4 1114
synchronized test1 1173
結論:直觀結論時如果單執行緒執行時,鎖機制對於效能並不影響;當多執行緒的時候鎖機制對於效能影響顯著;
比例:(617+631):(336+348) = 1.824
(892+936+935):(362+392+399)= 2.396
(992 + 1077 + 1114 + 1173) : (416 + 420 + 427 + 436) = 2.563
增量分析 執行緒增多單個執行緒執行時間增多: 執行緒一起分享cpu 時間,每個執行緒獲得cpu獨享時間減少,因此單個執行緒執行時間增多
執行緒增多,加鎖方法與平常方法時間比增加:等待執行緒越多,單個執行緒等待時間越長。但是為何增加加速度在減少,目前不清楚。
JVM對synchronized的優化 鎖膨脹
看到這裡,你應該明白了 為什麼synchronized 中只能傳物件,不能傳基礎資料型別?基礎資料型別不是物件,沒有物件頭,也就沒有鎖資訊 tips 建議對著markword結構圖看 執行緒a再次獲取鎖,因為是偏向鎖,所以非常快 執行緒a執行一會兒後,退出了同步 塊 執行緒b過來獲取鎖,因為鎖記錄的...
同步鎖synchronized中的類鎖,物件鎖
關於同步鎖的幾篇有用的文章 如果synchronized 修飾的非靜態方法 沒有static修飾 則鎖的是例項物件,物件鎖 synchronized this 使用的也是物件鎖 如果synchronized 修飾的是靜態方法,則鎖的是類物件,是類鎖 synchronized synchronized...
Synchronized 關鍵字中的類鎖 物件鎖
1 未加 synchronized 關鍵字 兩線程以並行方式執行 2 在非 static 方法上加 synchronized 關鍵字 兩線程以序列方式執行 3 在非 static 方法的內部 塊加上 synchronized this 4 在 static 方法前加上 synchronized 關鍵...