Java is indeed more low level than ActionScript. It's like comparing apples with oranges. While ActionScript handles it all transparently "under the hood", in Java you need to manage the asynchronous processing (threading) yourself.
Fortunately, in Java there's the java.util.concurrent
API which can do that in a nice manner.
Your problem can basically be solved as follows:
// Have one (or more) threads ready to do the async tasks. Do this during startup of your app.
ExecutorService executor = Executors.newFixedThreadPool(1);
// Fire a request.
Future<Response> response = executor.submit(new Request(new URL("http://google.com")));
// Do your other tasks here (will be processed immediately, current thread won't block).
// ...
// Get the response (here the current thread will block until response is returned).
InputStream body = response.get().getBody();
// ...
// Shutdown the threads during shutdown of your app.
executor.shutdown();
wherein Request
and Response
look like follows:
public class Request implements Callable<Response> {
private URL url;
public Request(URL url) {
this.url = url;
}
@Override
public Response call() throws Exception {
return new Response(url.openStream());
}
}
and
public class Response {
private InputStream body;
public Response(InputStream body) {
this.body = body;
}
public InputStream getBody() {
return body;
}
}
See also: