[英]synchronized block doesn't lock the object
有人解釋一下,為什么不synchronized block
鎖定變量_c
在這里?
public class static_thread implements Runnable{
private static Integer _c=0;
public static void main(String[] args) throws Throwable {
for(int i=0;i<100000;i++){
if(i%2==0){_c++;}
}
System.out.println("one thread: "+_c);
Thread[] t=new Thread[50];
_c=0;
for(int i=0;i<t.length;i++){
t[i]=new Thread(new static_thread(i, i*(100000/50)));
t[i].start();
}
for(Thread _:t){_.join();}
System.out.println("+one thread: "+_c);//wrong answer!
}
public void run() {
for(int i=s;i<(s+l);i++){
if(i%2==0){
synchronized (_c) {//y u no lock?!
_c++;//Inconsistence, not thread-safe, so what is synchronized block is doing here?
}
}
}
}
int s,l;
public static_thread(int s, int l) {
this.s = s;
this.l = l;
}
}
對於每次運行,我都會得到新的錯誤值。
通過做這個
_c++
您正在更改_c
持有的引用。 它相當於
int value = _c.intValue();
_c = Integer.valueOf(value + 1);
因此
synchronized (_c) {
每次在不同的對象上同步。
請記住, synchronized
塊鎖定對象,而不是變量。
您應始終使用與不能更改值的變量synchronized
,即。 讓它成為final
。
如果由於某種原因需要計數器,請考慮使用AtomicInteger
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.