【问题标题】:synchronized block doesn't lock the object同步块不锁定对象
【发布时间】:2014-04-15 21:47:53
【问题描述】:

有人解释一下,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;
  }
}

每次运行,我都会得到新的错误值。

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

    这样做

    _c++
    

    您正在更改 _c 持有的引用。相当于

    int value = _c.intValue();
    _c = Integer.valueOf(value + 1);
    

    因此

    synchronized (_c) {
    

    每次在不同的对象上同步。

    记住,synchronized 块锁定对象,而不是变量。

    您应该始终将synchronized 与不能更改值的变量一起使用,即。让它final

    如果您出于某种原因需要计数器,请考虑使用AtomicInteger

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多