gpt4 book ai didi

java - 在java中并行化网络请愿

转载 作者:行者123 更新时间:2023-11-29 05:55:44 24 4
gpt4 key购买 nike

我有一个 Response 对象,用于表示对 Web 服务的发布响应。鉴于此代码:

Response resp1= Server.request(a);
Response resp2= Server.request(b);
Response resp3= Server.request(c);
if (resp1.isOk() && resp2.isOk() && resp3.isOk()){
// Do stuff
}

由于服务器有点慢,我想在 3 个线程中并行处理请求。但我不知道如何让主线程等待结果并检索 3 个响应。

最佳答案

我想你可以做类似的事情来在 3 个线程中启动调用并等待它们终止:

private Response resp1, resp2, resp3;

protected void doRequests() {
Thread thread1 = new Thread() {
public void run() {
resp1= Server.request(a);
}
};
Thread thread2 = new Thread() {
public void run() {
resp1= Server.request(a);
}
};
Thread thread3 = new Thread() {
public void run() {
resp1= Server.request(a);
}
};

thread1.start();
thread2.start();
thread3.start();

try { thread1.join(); } catch(InterruptedException e) { }
try { thread2.join(); } catch(InterruptedException e) { }
try { thread3.join(); } catch(InterruptedException e) { }
}

关于java - 在java中并行化网络请愿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12200436/

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