2013-04-08 1 views
1

변수를 final로하지 않고 스레드 외부 변수에 액세스하는 방법은 무엇입니까?변수를 final로하지 않고 변수 외부 스레드에 액세스하는 방법

int x=0; 
Thread test = new Thread(){ 
public void run(){ 
x=10+20+20; //i can't access this variable x without making it final, and if i make  it.....     
       //final i can't assign value to it 
} 
};     
test.start(); 
+0

난이 자바라고 생각하고, 태그를 업데이트했습니다. – hmjd

답변

3

이상적으로, 당신은 ExecutorService.submit(Callable<Integer>)를 사용하고 값을 얻을 Future.get()를 호출 할 것이다. 스레드에 의해 공유 된 변이 형 변수는 예를 들어 동기화 동작을 요구한다. volatile, lock 또는 synchronized 키워드

Future<Integer> resultOfX = Executors.newSingleThreadExecutor().submit(new Callable<Integer>() { 
     @Override 
     public Integer call() throws Exception { 
      return 10 + 20 + 20; 
     } 
    }); 
    int x; 
    try { 
     x = resultOfX.get(); 
    } catch (InterruptedException ex) { 
     // never happen unless it is interrupted 
    } catch (ExecutionException ex) { 
     // never happen unless exception is thrown in Callable 
    } 
+1

스레드별로 공유 된 int를 변경해야하는 경우 CAS를 제공하는 AtomicInteger를 고려할 수 있습니다 –

관련 문제