我有一个 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/