当前位置:网站首页>[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());
}
边栏推荐
- 启牛商学院给的股票账户安全吗?能开户吗?
- Tick Data and Resampling
- 函数式接口和方法引用
- Amazon cloud technology community builder application window opens
- Redis exceeds the maximum memory error oom command not allowed when used memory & gt; ' maxmemory'
- Thanos Receiver
- RPA advanced (II) uipath application practice
- excel表格中选中单元格出现十字带阴影的选中效果
- Order by注入
- Develop scalable contracts based on hardhat and openzeppelin (II)
猜你喜欢

八大排序汇总

MySQL comparison operator in problem solving

RPA进阶(二)Uipath应用实践

mysql链表数据存储查询排序问题

TDSQL|就业难?腾讯云数据库微认证来帮你

在连接mysql数据库的时候一直报错

Tdsql | difficult employment? Tencent cloud database micro authentication to help you

C#多维数组的属性获取方法及操作注意

What is the relationship between digital transformation of manufacturing industry and lean production

R HISTOGRAM EXAMPLE QUICK REFERENCE
随机推荐
Tidb DM alarm DM_ sync_ process_ exists_ with_ Error troubleshooting
制造业数字化转型和精益生产什么关系
2022年4月17日五心红娘团队收获双份喜报
PowerBI中导出数据方法汇总
Webauthn - official development document
Supermarket (heap overload
mysql链表数据存储查询排序问题
由粒子加速器产生的反中子形成的白洞
Always report errors when connecting to MySQL database
TIPC messaging3
【云原生】2.5 Kubernetes 核心实战(下)
MySql存储过程游标遍历结果集
通过券商经理的开户二维码开股票账户安全吗?还是去证券公司开户安全?
flutter 问题总结
CentOS8之mysql基本用法
基于 Openzeppelin 的可升级合约解决方案的注意事项
预言机链上链下调研
Some suggestions for young people who are about to enter the workplace in the graduation season
Cluster Analysis in R Simplified and Enhanced
VS2019代码中包含中文内容导致的编译错误和打印输出乱码问题