当前位置:网站首页>[multithreading] the main thread waits for the sub thread to finish executing, and records the way to execute and obtain the execution result (with annotated code and no pit)
[multithreading] the main thread waits for the sub thread to finish executing, and records the way to execute and obtain the execution result (with annotated code and no pit)
2022-07-02 11:43:00 【I'm a girl】
Pretend a lot of words , Look directly at the code , Xiaobai is not afraid of comments on each line , It can be modified adaptively
The important thing is to remind , Most multithreads report errors , Or the data is not right , Please check the rejection policy of the thread pool
// Atomic counter , Many times, I'm not sure how many times it needs to be executed to prevent errors
private static final AtomicInteger atomicInteger = new AtomicInteger(0);
// Thread configuration , Blocking queues , The strategy mode is reasonably configured , It can ensure that the thread will not lose data
// Other thread pool parameters , You can modify it according to your needs , If you don't understand the corresponding parameters, you can read another article
//【 Multithreading 】ThreadPoolExecutor Like 10000 words source code analysis ( Annotation super detailed )
// Modify the pool size as needed
private static final ExecutorService pool = new ThreadPoolExecutor(2, 4,
1000, TimeUnit.SECONDS,
new LinkedBlockingDeque<Runnable>(100),
new ThreadPoolExecutor.CallerRunsPolicy());
// Future The interface has blocking synchronization , The efficiency of such code will be greatly reduced
// Interface CompletionService It can solve such problems .
private static final CompletionService<Integer> completionService = new ExecutorCompletionService<>(pool);
public static void main(String[] args) {
// Start execution
System.out.println(new Date());
// Start timing
for (int i = 0; i < 3; i++) {
// Counter plus 1
atomicInteger.getAndIncrement();
Callable<Integer> callable = ()-> {
// Sub threads execute business code
int num = 1000;
int s = 0;
for (int j = 0; j < num; j++) {
s += j;
}
Thread.sleep(2000);
System.out.println("t Over s =" + s);
// Return execution result
return s;
};
try {
// The execution speed is too fast to see the effect , Get some sleep
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Perform tasks
completionService.submit(callable);
}
// Get the value of the atomic counter , Loop to get the return value
for (int i = 0; i < atomicInteger.get(); i++) {
try {
// CompletionService Of take() Method will first return the earliest executed Callable Return value
// Which task is completed first , Whichever task returns the value first, print it first , Don't wait for the first Callable object .
// CompletionService If no task in the interface has been executed
// be take(). get() The method is still blocked .
Integer s = completionService.take().get();// Two exceptions need to be caught
System.out.println("s : " + s);
}catch (InterruptedException | ExecutionException e){
e.printStackTrace();
}
}
// pool.shutdown(); Close smoothly , New threads are not allowed to join , The running can be closed after running .
// pool.shutdownNow(); Violent closure . New threads are not allowed to join , And stop directly to the thread in progress .
pool.shutdown();
System.out.println(new Date());
}
边栏推荐
- MTK full dump抓取
- Approximate sum count (approximate
- spritejs
- Is bond fund safe? Does the bond buying foundation lose principal?
- PYQT5+openCV项目实战:微循环仪图片、视频记录和人工对比软件(附源码)
- tqdm的多行显示与单行显示
- Order by注入
- Tidb DM alarm DM_ sync_ process_ exists_ with_ Error troubleshooting
- 微信小程序利用百度api达成植物识别
- Jinshanyun - 2023 Summer Internship
猜你喜欢
[cloud native] 2.5 kubernetes core practice (Part 2)
What is the relationship between digital transformation of manufacturing industry and lean production
A sharp tool for exposing data inconsistencies -- a real-time verification system
【IDEA】使用插件一键逆向生成代码
Win11 arm system configuration Net core environment variable
vant tabs组件选中第一个下划线位置异常
Summary of data export methods in powerbi
map集合赋值到数据库
TDSQL|就业难?腾讯云数据库微认证来帮你
Wechat applet uses Baidu API to achieve plant recognition
随机推荐
tidb-dm报警DM_sync_process_exists_with_error排查
ros缺少catkin_pkg
ren域名有价值吗?值不值得投资?ren域名的应用范围有哪些?
ros gazebo相关包的安装
Order by注入
STM32 single chip microcomputer programming learning
vant tabs组件选中第一个下划线位置异常
Jinshanyun - 2023 Summer Internship
C# 文件与文件夹操作
【多线程】主线程等待子线程执行完毕在执行并获取执行结果的方式记录(有注解代码无坑)
From the perspective of attack surface, see the practice of zero trust scheme of Xinchuang
C#多维数组的属性获取方法及操作注意
由粒子加速器产生的反中子形成的白洞
PHP tea sales and shopping online store
ImportError: cannot import name ‘Digraph‘ from ‘graphviz‘
Always report errors when connecting to MySQL database
MySQL linked list data storage query sorting problem
ASTParser 解析含有emum 枚举方法的类文件的踩坑记
Thanos Receiver
Attribute acquisition method and operation notes of C # multidimensional array