What you are looking for is probably the Callable<V>
interface in place of Runnable
, and retrieving the value with a Future<V>
object, which also lets you wait until the value has been computed. You can achieve this with an ExecutorService
, which you can get from Executors.newSingleThreadExecutor()
.
public void test() {
int x;
ExecutorService es = Executors.newSingleThreadExecutor();
Future<Integer> result = es.submit(new Callable<Integer>() {
public Integer call() throws Exception {
// the other thread
return 2;
}
});
try {
x = result.get();
} catch (Exception e) {
// failed
}
es.shutdown();
}