2014-04-15 2 views
3

누군가가 설명합니다. 왜 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++ 

이렇게함으로써

답변

9

당신은 _c 들고있는 기준이 변경됩니다. 따라서

synchronized (_c) { 

마다 다른 물체에 동기화

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

동일하다.

synchronized 변수가 아닌 블록 잠금.

값을 변경할 수없는 변수와 함께 항상 synchronized을 사용해야합니다. 그것을 final하십시오.

어떤 이유로 카운터가 필요한 경우 AtomicInteger을 사용해보십시오.

+0

많은 분들께 감사드립니다. 당신의 도움을 주셔서 감사합니다. –

관련 문제