Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 同步块不';不要锁定对象_Java_Multithreading - Fatal编程技术网

Java 同步块不';不要锁定对象

Java 同步块不';不要锁定对象,java,multithreading,Java,Multithreading,有人解释,为什么不在这里锁定变量\u 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: "

有人解释,为什么不在这里锁定变量
\u 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=0;
公共静态void main(字符串[]args)抛出可丢弃的{
对于(int i=0;i,通过这样做

_c++
您正在更改
\u c
保存的引用。它相当于

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

synchronized (_c) {
每次在不同的对象上同步

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

您应该始终将
synchronized
与无法更改值的变量一起使用,即使其成为
final

如果出于某种原因需要计数器,请考虑使用<代码> AtomicInteger < /代码> ./P>