当前位置:网站首页>[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());
}
边栏推荐
- Always report errors when connecting to MySQL database
- Writing contract test cases based on hardhat
- 基于Hardhat和Openzeppelin开发可升级合约(二)
- 2022年遭“挤爆”的三款透明LED显示屏
- SSRF
- Thanos Receiver
- 对毕业季即将踏入职场的年轻人的一点建议
- Develop scalable contracts based on hardhat and openzeppelin (II)
- 念念不忘,必有回响 | 悬镜诚邀您参与OpenSCA用户有奖调研
- Native method merge word
猜你喜欢

Importerror: impossible d'importer le nom « graph» de « graphviz»

抖音海外版TikTok:正与拜登政府敲定最终数据安全协议

TIPC addressing 2

2022年4月17日五心红娘团队收获双份喜报

Win11 arm system configuration Net core environment variable

TIPC messaging3

微信小程序利用百度api达成植物识别

由粒子加速器产生的反中子形成的白洞

揭露数据不一致的利器 —— 实时核对系统

Redis exceeds the maximum memory error oom command not allowed when used memory & gt; ' maxmemory'
随机推荐
[idea] use the plug-in to reverse generate code with one click
Verilog and VHDL signed and unsigned number correlation operations
Native method merge word
Homer forecast motif
Some things configured from ros1 to ros2
Writing contract test cases based on hardhat
liftOver进行基因组坐标转换
ImportError: cannot import name ‘Digraph‘ from ‘graphviz‘
基于Hardhat和Openzeppelin开发可升级合约(一)
R HISTOGRAM EXAMPLE QUICK REFERENCE
【IDEA】使用插件一键逆向生成代码
TIPC addressing 2
ros缺少catkin_pkg
6方面带你认识LED软膜屏 LED软膜屏尺寸|价格|安装|应用
亚马逊云科技 Community Builder 申请窗口开启
QT获取某个日期是第几周
ImportError: cannot import name ‘Digraph‘ from ‘graphviz‘
MTK full dump抓取
Tick Data and Resampling
Internship report skywalking distributed link tracking?