当前位置:网站首页>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
边栏推荐
- Test the time required for Oracle library to create an index with 7 million data in a common way
- Generate 32-bit UUID in Oracle
- Using open to open a file in JNI returns a - 1 problem
- torch. Where can transfer gradient
- Set Jianyun x Feishu Shennuo to help the enterprise operation Department realize office automation
- SHA512 / 384 principle and C language implementation (with source code)
- [machine learning] Note 4. KNN + cross validation
- Core concepts of microservice architecture
- AI21 Labs | Standing on the Shoulders of Giant Frozen Language Models(站在巨大的冷冻语言模型的肩膀上)
- Ora-16047 of a DG environment: dgid mismatch between destination setting and target database troubleshooting and listening vncr features
猜你喜欢

SAP ui5 application development tutorial 72 - animation effect setting of SAP ui5 page routing

MySQL and PgSQL time related operations
![[point cloud series] pointfilter: point cloud filtering via encoder decoder modeling](/img/da/02d1e18400414e045ce469425db644.png)
[point cloud series] pointfilter: point cloud filtering via encoder decoder modeling

Dolphin scheduler source package Src tar. GZ decompression problem

Stack protector under armcc / GCC

Double pointer instrument panel reading (I)

Window analysis function last_ VALUE,FIRST_ VALUE,lag,lead

Information: 2021 / 9 / 29 10:01 - build completed with 1 error and 0 warnings in 11S 30ms error exception handling

The query did not generate a result set exception resolution when the dolphin scheduler schedules the SQL task to create a table

Machine learning -- PCA and LDA
随机推荐
Static interface method calls are not supported at language level '5'
Detailed explanation of Oracle tablespace table partition and query method of Oracle table partition
Example of specific method for TIA to trigger interrupt ob40 based on high-speed counter to realize fixed-point machining action
Longitude and latitude position of provincial capitals in China
Feature Engineering of interview summary
pycharm Install packages failed
Dolphin scheduler scheduling spark task stepping record
Tersus notes employee information 516 MySQL query (time period uniqueness judgment of 2 fields)
Dolphin scheduler source package Src tar. GZ decompression problem
sys. dbms_ scheduler. create_ Job creates scheduled tasks (more powerful and rich functions)
Opening: identification of double pointer instrument panel
TIA博途中基於高速計數器觸發中斷OB40實現定點加工動作的具體方法示例
Two ways to deal with conflicting data in MySQL and PG Libraries
面试官给我挖坑:URI中的 “//” 有什么用?
On the bug of JS regular test method
Antd design form verification
Troubleshooting of expdp export error when Oracle table has logical bad blocks
Oracle creates tablespaces and modifies user default tablespaces
[andorid] realize SPI communication between kernel and app through JNI
浅谈js正则之test方法bug篇