2013-04-08 67 views
1

如何访问变量外线程而不使变量成为最终变量?如何访问变量外线程而不使变量成为最终变量

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

我觉得这是Java和更新了标签。 – hmjd 2013-04-08 10:53:23

回答

3

理想情况下,你可能需要使用ExecutorService.submit(Callable<Integer>),然后调用Future.get()获得的价值。线程共享的变量变量需要同步动作,例如volatilelock或​​关键字

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,你可能要考虑AtomicInteger,它提供了CAS – 2013-06-21 18:03:44