# **[JAVA] 多執行續處理查詢** ## [實作目的] 工作上遇到需要去call 不相關的A、B、C、D API之後,將查到的資料彙整成一個 List 的功能,但資料庫內資料量太大造成一一查詢效能低落,於是改為 4 個執行續分頭作業後再彙整。 ### 1.建立固定 4 個執行續的執行續池: ```java= ExecutorService executor = Executors.newFixedThreadPool(4,new ThreadFactory() { int count = 1; @Override public Thread newThread(@NonNull Runnable runnable) { return new Thread(runnable, "ABCD-executor-" + count++); } }); ``` ### 2.宣告 AbdcDTOs 來做存放容器,並分別查詢後彙整,關閉執行續。 ```java= List<AbcdDTO> AbcdDTOs = new ArrayList<>(); CompletableFuture<Void> future1 = CompletableFuture.runAsync(() ->AbcdDTOs.addAll(AService.getA()),executor); CompletableFuture<Void> future2 = CompletableFuture.runAsync(() ->AbcdDTOs.addAll(BService.getB()),executor); CompletableFuture<Void> future3 = CompletableFuture.runAsync(() ->AbcdDTOs.addAll(CService.getC()),executor); CompletableFuture<Void> future4 = CompletableFuture.runAsync(() ->AbcdDTOs.addAll(DService.getD()),executor); CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(future1, future2, future3, future4); combinedFuture.join(); executor.shutdown(); ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up