当前位置:网站首页>[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());
}
边栏推荐
- PLC-Recorder快速监控多个PLC位的技巧
- Summary of flutter problems
- Skills of PLC recorder in quickly monitoring multiple PLC bits
- ImportError: cannot import name ‘Digraph‘ from ‘graphviz‘
- 高德根据轨迹画线
- Visualization of chip SEQ data by deeptools
- Mongodb learning and sorting (condition operator, $type operator, limit() method, skip() method and sort() method)
- MySQL comparison operator in problem solving
- CTF record
- 对毕业季即将踏入职场的年轻人的一点建议
猜你喜欢

CTF record

PowerBI中导出数据方法汇总

Multi line display and single line display of tqdm

Mmrotate rotation target detection framework usage record

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

ctf 记录

II Stm32f407 chip GPIO programming, register operation, library function operation and bit segment operation

GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R

八大排序汇总

ImportError: cannot import name ‘Digraph‘ from ‘graphviz‘
随机推荐
念念不忘,必有回响 | 悬镜诚邀您参与OpenSCA用户有奖调研
sql left join 主表限制条件写在on后面和写在where后面的区别
VS2019代码中包含中文内容导致的编译错误和打印输出乱码问题
基于Hardhat编写合约测试用例
ASTParser 解析含有emum 枚举方法的类文件的踩坑记
The difference between SQL left join main table restrictions written after on and where
Jenkins installation
JS——每次调用从数组里面随机取一个数,且不能与上一次为同一个
LVM operation
Principe du contrat évolutif - delegatecall
deepTools对ChIP-seq数据可视化
【IDEA】使用插件一键逆向生成代码
ren域名有价值吗?值不值得投资?ren域名的应用范围有哪些?
spritejs
Tdsql | difficult employment? Tencent cloud database micro authentication to help you
从ros1到ros2配置的一些东西
ImportError: cannot import name ‘Digraph‘ from ‘graphviz‘
Some suggestions for young people who are about to enter the workplace in the graduation season
MTK full dump抓取
Order by injection