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(开发者_StackOverflow)
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();
}
}
Use a Callable<String>
instead, submit it to an ExecutorService
, and then call get()
on the Future<String>
it returns when you submit it.
精彩评论