views:

61

answers:

3

Hi to all,

i want to call a method that returns a string value. Actually this string value is an instance variable, and run method put the value of the string.

So, i want to call a method to get the string value updated by thread run() method..

How i do it...?

Plz anyone help me..

Saravanan

+1  A: 

Use a Callable<String> instead, submit it to an ExecutorService, and then call get() on the Future<String> it returns when you submit it.

Mark Peters
sorry, i couldn't get u
Saravanan
Ahh yeah, Tim took my answer and gave you a good example so I'll leave it at that.
Mark Peters
+5  A: 

Check out Callable which is a Runnable that can return a result.

You use it like this:

You write a Callable instead of a Runnable, for example:

public class MyCallable implements Callable<Integer> {
  public Integer call () {
    // do something that takes really long...
    return 1;
  }
}

You kick it of by submitting it to an ExecutionService:

ExecutorService es = Executors.newSingleThreadExecutor ();
Future<Integer> task = es.submit(new MyCallable());

You get back the FutureTask handle which will hold the result once the task is finished:

Integer result = task.get ();

FutureTask provides more methods, like cancel, isDone and isCancelled to cancel the execution and ask for the status. The get method itself is blocking and waits for the task to finish. check out the javadoc for details.

Tim Büthe
Why create a new FutureTask instead of just submitting the Callable directly? I think that's unnecessary.
Mark Peters
@Mark: You are right, I just changed that.
Tim Büthe
+1  A: 
Class Whatever implements Runnable {
    private volatile String string;

    @Override
    public void run() {
        string = "whatever";
    }

    public String getString() {
        return string;
    }

    public void main(String[] args) throws InterruptedException {
        Whatever whatever = new Whatever();
        Thread thread = new Thread(whatever);
        thread.start();
        thread.join();
        String string = whatever.getString();
    }
}
Steve Emmerson