gpt4 book ai didi

java - AsyncHttpClient (Java) onComplete() : Does onCompleted() run on the separate thread?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:53:02 25 4
gpt4 key购买 nike

查看Java库中的代码块AsyncHttpClient ,客户端启动一个新线程(Future)来发出请求。回调是在同一个线程上发生,还是在“主”线程上运行(在本例中,是调用 new AsyncHttpClient() 的线程?

import com.ning.http.client.*;
import java.util.concurrent.Future;

AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
asyncHttpClient.prepareGet("http://www.ning.com/ ").execute(new AsyncCompletionHandler<Response>(){

@Override
public Response onCompleted(Response response) throws Exception{
// Do something with the Response
// ...
return response;
}

@Override
public void onThrowable(Throwable t){
// Something wrong happened.
}
});

最佳答案

the client starts a new thread (a Future) to make the request.

没有。 Future 基本上意味着:这个方法已经返回但还没有完成处理。处理将在后台继续(在您无法控制的其他线程中),并将在 future 的某个时间完成。您可以询问此 Future 对象以查看 future 是否已经到来(处理已完成)。您没有自己创建任何线程。

想想ExecutorService。您正在提交一些待完成的任务并等待结果。但是您不会阻塞,而是得到一个 Future,它会在您提交的任务到达线程池并被处理后立即返回结果。

Will the callback happen on the same thread, or will it run on the "main" thread

都没有。当响应返回时,您的线程(调用 AsyncHttpClient.execute() 的线程)很可能正在做一些完全不同的事情。也许它服务于另一个客户或者已经死了。您不能只代表一些 线程调用任意代码。

实际上这段代码会被AsyncHttpClient库创建的内部NIO线程执行。您完全无法控制此线程。但您必须记住,这将异步发生,因此如果您访问全局对象,可能需要同步或某些锁定。

关于java - AsyncHttpClient (Java) onComplete() : Does onCompleted() run on the separate thread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11764614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com