如何在不使变量最终的情况下访问变量外部线程

时间:2013-04-08 09:50:34

标签: java multithreading variables assign

如何在不使变量最终的情况下访问变量外部线程?

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

1 个答案:

答案 0 :(得分: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
    }