简体   繁体   中英

How to access variable outside thread without making the variable final

How to access variable outside thread without making the variable 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();

Ideally, you would want to use ExecutorService.submit(Callable<Integer>) and then call Future.get() to obtain the value. Mutating variable shared by threads require synchronize action eg volatile , lock or synchronized key word

    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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM