user1416312
user1416312

Reputation: 3

How to modify variables while thread is running

At first, I used the Runnable and built a 'while(true)' loop for continuing handling my job. Now I find something difficult while changing to use Callable.

package com;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableAndFuture {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ChildCallbale childCallbale = new ChildCallbale();
        FutureTask<Integer> future = new FutureTask<Integer>(childCallbale);
        Thread thread = new Thread(future);
        thread.start();
        childCallbale.setVar(1);
        System.out.println(future.get());
        childCallbale.setVar(2);
        System.out.println(future.get());
    }
}
class ChildCallbale implements Callable<Integer>{
    private int var;

    public void setVar(int var){
        this.var = var;
    }
    @Override
    public Integer call() throws Exception {
        Thread.sleep(2000);
        return var;
    }
}

As you see, I want to get different results as I excpeted. Unfortunately, the 2 results are equal with 1. Not only I want to get know how to realize my requirement, I also want to know the reason why my code turns to be incorrect. Thanks in advance.

Upvotes: 0

Views: 79

Answers (1)

UniversE
UniversE

Reputation: 2507

The get() method of a future waits for computation to be finished. So it waits the two seconds your thread sleeps. Then the result is 1. And the result stays 1, because the thread is not re-run (and shouldn't be re-run!).

So the second setVar has no effect on the result.

Upvotes: 1

Related Questions