如何在不使变量最终的情况下访问变量外部线程?
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 :(得分: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
}