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

标签 java android multithreading

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

相关文章:

java - Android Intent/IntentService 的空指针异常

android - 如何从可绘制文件夹中获取资源 - AndEngine

java - 为什么 LogWriter 中的竞争条件会导致生产者阻塞? [实践中的并发]

python - 我的代码会增加线程吗?

java - 在代号一中显示空白谷歌地图

java - Azure 脱机同步来自 1 :n relationship in Android mobile app 的数据

java - 是否有更干净的方法使用 RxJava 来适应标准观察者/监听器服务?

java - 每天后重复闹钟

.net - "Hello World"用于基于任务的异步模式?

java - WebDriver 等待网站完全加载