当前位置:网站首页>Use future and countdownlatch to realize multithreading to execute multiple asynchronous tasks, and return results after all tasks are completed
Use future and countdownlatch to realize multithreading to execute multiple asynchronous tasks, and return results after all tasks are completed
2022-04-23 13:44:00 【0oIronhide】
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/** * use Future And CountDownLatch Implement multithreading to execute multiple asynchronous tasks , After all the tasks are completed, the results will be returned */
public class TestFuture {
public static void main(String[] args) {
TestFuture testFuture = new TestFuture();
// The initial number is three tasks
int taskCount = 3;
List<Future<String>> futures = new ArrayList<>(taskCount);
// CountDownLatch As a decrement counter , A thread completes a task , Counter minus one , Reduced to 0 When, it means that the task has been completed
CountDownLatch downLatch = new CountDownLatch(taskCount);
ExecutorService executorService = new ThreadPoolExecutor
(taskCount, 5, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));
for (int i = 0; i < taskCount; i++) {
// Start three asynchronous tasks
Future<String> future = executorService.submit(testFuture.executeTask(i, downLatch));
futures.add(future);
}
System.out.println("do other things");
try {
// stay downLatch Not for 0 when , The main thread will block here
downLatch.await();
executorService.shutdown();
// adopt future To get the results
List<String> result = testFuture.getFutureResult(futures);
for (String s : result) {
System.out.println(s);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public Callable<String> executeTask(int i, CountDownLatch downLatch) {
return () -> {
Thread.sleep(i * 1000L);
downLatch.countDown();
return "Result " + Thread.currentThread().getName();
};
}
public List<String> getFutureResult(List<Future<String>> futures) {
List<String> result = new ArrayList<>(3);
for (Future<String> future : futures) {
if (future.isDone() && !future.isCancelled()) {
try {
result.add(future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
return result;
}
}
版权声明
本文为[0oIronhide]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230600131809.html
边栏推荐
- ./gradlew: Permission denied
- AI21 Labs | Standing on the Shoulders of Giant Frozen Language Models(站在巨大的冷冻语言模型的肩膀上)
- NPM err code 500 solution
- Feature Engineering of interview summary
- Apache seatunnel 2.1.0 deployment and stepping on the pit
- Oracle index status query and index reconstruction
- At the same time, the problems of height collapse and outer margin overlap are solved
- Processbuilder tool class
- Campus takeout system - "nongzhibang" wechat native cloud development applet
- Failure to connect due to improper parameter setting of Rac environment database node. Troubleshooting
猜你喜欢
Explanation of input components in Chapter 16
[point cloud series] so net: self organizing network for point cloud analysis
切线空间(tangent space)
SAP ui5 application development tutorial 72 - trial version of animation effect setting of SAP ui5 page routing
Detailed explanation of constraints of Oracle table
SHA512 / 384 principle and C language implementation (with source code)
[point cloud series] learning representations and generative models for 3D point clouds
集简云 x 飞书深诺,助力企业运营部实现自动化办公
Dolphin scheduler configuring dataX pit records
SAP UI5 应用开发教程之七十二 - SAP UI5 页面路由的动画效果设置
随机推荐
[tensorflow] sharing mechanism
[point cloud series] pointfilter: point cloud filtering via encoder decoder modeling
PG library to view the distribution keys of a table in a certain mode
Operations related to Oracle partition
Publish custom plug-ins to local server
Oracle job scheduled task usage details
面试官给我挖坑:URI中的 “//” 有什么用?
Resolution: argument 'radius' is required to be an integer
Oracle view related
The query did not generate a result set exception resolution when the dolphin scheduler schedules the SQL task to create a table
Software test system integration project management engineer full truth simulation question (including answer and analysis)
Oracle creates tablespaces and modifies user default tablespaces
QT调用外部程序
Oracle generates millisecond timestamps
The interviewer dug a hole for me: what's the use of "/ /" in URI?
Oracle clear SQL cache
Android clear app cache
Processing of ASM network not automatically started in 19C
19c RAC steps for modifying VIP and scanip - same network segment
Bottomsheetdialogfragment + viewpager + fragment + recyclerview sliding problem