Java确实比ActionScript更低级。这就像比较苹果和橘子。虽然ActionScript处理所有透明的“底层”,在Java中,你需要自己管理异步处理(线程)。
幸运的是,在Java中有java.util.concurrent API可以以一种很好的方式做到这一点。
你的问题基本上可以解决如下:
// 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 = 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();
其中请求和响应如下:
public class Request implements Callable {
private URL url;
public Request(URL url) {
this.url = url;
}
@Override
public Response call() throws Exception {
return new Response(url.openStream());
}
}
和
public class Response {
private InputStream body;
public Response(InputStream body) {
this.body = body;
}
public InputStream getBody() {
return body;
}
}
也可以看看:
> Lesson: Concurrency – 一个java.util.concurrent教程。