gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:45:52 28 4
gpt4 key购买 nike

如何在不使变量成为final的情况下访问线程外的变量?

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

最佳答案

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

    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
}

关于java - 如何在不使变量最终化的情况下访问线程外的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15876110/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com