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 can I do it...?
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With