public class SychronizdDemo {
static Integer count=0;
public static void incr(){
synchronized (count) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
}
public static void main(String[] args) throws IOException, InterruptedException {
for(int i=0;i<1000;i++){
new Thread(()->SychronizdDemo.incr()).start();
}
Thread.sleep(5000);
System.out.println("result:"+count);
}
}
為什么sleep不會釋放鎖而輸出的結果卻是小于1000的數呢???
uj5u.com熱心網友回復:
個人認為Integer在數字0-127的時候有java默認的記憶體地址,所以每次更新了count之后,其實監視器已經改變了不能保證一定是執行緒安全的uj5u.com熱心網友回復:
說的有些問題,應該是每次++之后,count都不再是原來那個count了,他會重新return new integer,所以監視器一直在變。還有integer的快取范圍是-128-127
uj5u.com熱心網友回復:
sleep本身就不會釋放鎖,count++后count物件變了,所以用類物件加鎖就可以了。uj5u.com熱心網友回復:
樓上正解。[align=center]鎖的物件變了。你始終在改變Integer。
程式改成這樣就對了(專門弄個lock物件來作為鎖):
public class SychronizdDemo {
static Object lock = new Object();
static Integer count=0;
public static void incr(){
synchronized (lock) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
System.out.println(count);
}
}
public static void main(String[] args) throws IOException, InterruptedException {
for(int i=0;i<1000;i++){
new Thread(()->SychronizdDemo.incr()).start();
}
Thread.sleep(5000);
System.out.println("result:"+count);
}
}
可以看看我的接個博客:https://blog.csdn.net/Kurry4ever_/article/details/109557532
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/214166.html
標籤:Java SE
