2013-04-08 74 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