單個執行緒等待 多個執行緒 任務 完成後,進行彙總合併

2022-06-26 18:27:09 字數 1294 閱讀 5068

public class testcountdownlatch1  catch (interruptedexception e) finally

}).start();

}countdownlatch.await();// 主線程在阻塞,當計數器==0,就喚醒主線程往下執行。

system.out.println("主線程:在所有任務執行完成後,進行結果彙總");}}

這種場景應該是用的最多了,比如我們開啟乙個電商的個人中心頁面,我們需要呼叫,使用者資訊介面、使用者訂單介面、使用者會員資訊等介面,然後合併後一起給到前端,假設每個介面最長耗時為1s,如果我們同步呼叫的話最大耗時時間是3s,如果我們採用非同步呼叫然後合併結果,所以最大的耗時時間是3s。每個介面呼叫返回資料後呼叫countdown方法,讓計數器進行減1,當把計數器減為0時的這個執行緒會去喚醒主線程,讓它繼續往下走。

個人理解:

long start = system.currenttimemillis();

int count = 3;

countdownlatch countdownlatch = new countdownlatch(count);

for (int i = 0; i < count; i++)

if(1 == finali)

if(2 == finali)

system.out.println("finish" + index + thread.currentthread().getname());

} catch (interruptedexception e) finally

}).start();

}countdownlatch.await();// 主線程在阻塞,當計數器==0,就喚醒主線程往下執行。

system.out.println("主線程:在所有任務執行完成後,進行結果彙總");

system.out.println(system.currenttimemillis()-start);

}public void t1() throws interruptedexception

public void t2() throws interruptedexception

public void t3() throws interruptedexception

執行結果

位址

c 多執行緒網路請求,等待所有執行緒完成後更新UI

最近專案中需要迴圈進行網路請求拉取使用者資訊 每個使用者資訊都需要一次網路請求 拉取完成後需要通知介面更新ui。實現方法是使用c 提供的manualresetevent,相當於乙個標記,在每個執行緒中插入這個標記。再啟動乙個執行緒迴圈監聽這個標記,直到所有執行緒都執行完畢則更新ui。public l...

python多執行緒完成多個任務

執行緒 執行緒可以理解成執行 的分支,執行緒是執行對應的 的,cpu排程執行緒去執行對應 importtime importthreading 跳舞的任務 defdance 獲取當前執行 的執行緒 current thread threading.current thread print dance...

Python等待所有執行緒任務完成

import threading import time import random def takesleep id,name print name id 執行緒開始執行.time.sleep random.randint 0,3 print name id 執行緒任務結束 print 主程式開始...