当前位置:网站首页>[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());
}
边栏推荐
- ren域名有价值吗?值不值得投资?ren域名的应用范围有哪些?
- ImportError: cannot import name ‘Digraph‘ from ‘graphviz‘
- CTF record
- Programmer growth Chapter 6: how to choose a company?
- Is the Ren domain name valuable? Is it worth investing? What is the application scope of Ren domain name?
- Is the stock account given by qiniu business school safe? Can I open an account?
- Multi line display and single line display of tqdm
- Mongodb learning and sorting (condition operator, $type operator, limit() method, skip() method and sort() method)
- VS2019代码中包含中文内容导致的编译错误和打印输出乱码问题
- Amazon cloud technology community builder application window opens
猜你喜欢

Digital transformation takes the lead to resume production and work, and online and offline full integration rebuilds business logic

Pit of the start attribute of enumrate

制造业数字化转型和精益生产什么关系

Redis超出最大内存错误OOM command not allowed when used memory &gt; 'maxmemory'

Mongodb learning and sorting (condition operator, $type operator, limit() method, skip() method and sort() method)

Verilog 和VHDL有符号数和无符号数相关运算

Map set assignment to database

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

Basic usage of MySQL in centos8

ren域名有价值吗?值不值得投资?ren域名的应用范围有哪些?
随机推荐
Jinshanyun - 2023 Summer Internship
ros缺少xacro的包
Functional interfaces and method references
The difference between SQL left join main table restrictions written after on and where
Pit of the start attribute of enumrate
C#基于当前时间,获取唯一识别号(ID)的方法
C#多维数组的属性获取方法及操作注意
Order by injection
基于Hardhat和Openzeppelin开发可升级合约(一)
Tick Data and Resampling
基于 Openzeppelin 的可升级合约解决方案的注意事项
MySQL比较运算符IN问题求解
6方面带你认识LED软膜屏 LED软膜屏尺寸|价格|安装|应用
【IDEA】使用插件一键逆向生成代码
Approximate sum count (approximate
从ros1到ros2配置的一些东西
PYQT5+openCV项目实战:微循环仪图片、视频记录和人工对比软件(附源码)
Wechat applet uses Baidu API to achieve plant recognition
sqlite 修改列类型
预言机链上链下调研