1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| 一、理论 1、Java 中可以用: -CountDownLatch:等待多个线程完成后统一上传 -ConcurrentLinkedQueue:线程安全收集数据 -ExecutorService + Future:收集结果后统一处理上传
2、Kotlin 中可以用: -coroutine + async/await:并发获取信息,使用 awaitAll 统一上传 -Channel 或 Flow:收集数据后集中处理上传操作
二、示例 2.1-Java 方案: 使用 CountDownLatch 或 Future + ExecutorService 等方式等待所有子线程完成,再统一上传。 例如:
CountDownLatch latch = new CountDownLatch(taskCount); for (...) { executor.execute(() -> { // 获取信息 latch.countDown(); }); } latch.await(); // 统一上传
2.2-Kotlin 方案: 使用协程 async + awaitAll 实现并发处理后统一上传: val results = coroutineScope { list.map { async { // 获取信息 } }.awaitAll() } // 统一上传 results
|