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();
4

1 回答 1

3

理想情况下,您希望使用ExecutorService.submit(Callable<Integer>)然后调用Future.get()来获取值。线程共享的变异变量需要同步操作,例如volatilelocksynchronized关键字

    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
    }
于 2013-06-21T12:06:02.473 回答