当前位置:网站首页>JUC summary
JUC summary
2022-07-26 13:24:00 【weixin_ forty-three million seven hundred and sixty-six thousan】
java.util.concurrent
1. CyclicBarrier
- Reusable barrier : When the number of request threads reaches a certain number, it will be released , After release, the number of threads to be blocked will be reset again
- Code example
public static void testCyclicBarrier(){
CyclicBarrier cyclicBarrier =
new CyclicBarrier(4, () -> System.out.println(Thread.currentThread().getName()+": Full start the game !"));
class Task implements Runnable{
private CyclicBarrier cyclicBarrier;
public Task(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()+": Be ready ");
cyclicBarrier.await();// Once in, it is blocked and added to the waiting queue
System.out.println(Thread.currentThread().getName()+": In the game ...");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
for (int i = 0; i < 8; i++) {
try {
TimeUnit.MILLISECONDS.sleep(500);// Increase the interval , Make the effect more intuitive and clear
new Thread(new Task(cyclicBarrier)," Threads _"+i).start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
- Console output
Threads _0: Be ready
Threads _1: Be ready
Threads _2: Be ready
Threads _3: Be ready
Threads _3: Full start the game !
Threads _3: In the game ...
Threads _0: In the game ...
Threads _1: In the game ...
Threads _2: In the game ...
Threads _4: Be ready
Threads _5: Be ready
Threads _6: Be ready
Threads _7: Be ready
Threads _7: Full start the game !
Threads _7: In the game ...
Threads _4: In the game ...
Threads _5: In the game ...
Threads _6: In the game ...
2. Semaphore
- Semaphore It's a semaphore , Its function is to limit current for single machine application , Limit the concurrency of an interface
- Semaphore The remaining license is through AQS Medium state Property , Obtaining a license is to reduce the value , Releasing the license is to increase the value , When there is not enough permission , The thread will join the blocking queue and wait for other threads to release the license and wake up .
- Code example
public static void testSemaphore(){
Semaphore semaphore = new Semaphore(3);
class RUN implements Runnable{
private Semaphore semaphore;
public RUN(Semaphore semaphore) {
this.semaphore = semaphore;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
try {
System.out.println(" Remaining licenses :" + semaphore.availablePermits());
semaphore.acquire();// If the license is insufficient , The current thread will be blocked and added to the waiting queue , Until a license is available , Will be awakened
System.out.println(threadName + ": Get a license , Perform tasks ");
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
System.out.println(threadName + ": To complete the task , Release license ");
semaphore.release();
}
}
}
for (int i = 0; i < 12; i++) {
new Thread(new RUN(semaphore)," Threads "+i).start();
}
}
- Console output
Remaining licenses :3
Threads 0: Get a license , Perform tasks
Remaining licenses :2
Threads 3: Get a license , Perform tasks
Remaining licenses :1
Threads 4: Get a license , Perform tasks
Remaining licenses :0
Remaining licenses :0
Remaining licenses :0
Remaining licenses :0
Remaining licenses :0
Remaining licenses :0
Remaining licenses :0
Remaining licenses :0
Remaining licenses :0
Threads 3: To complete the task , Release license
Threads 0: To complete the task , Release license
Threads 7: Get a license , Perform tasks
Threads 8: Get a license , Perform tasks
Threads 4: To complete the task , Release license
Threads 11: Get a license , Perform tasks
Threads 7: To complete the task , Release license
Threads 11: To complete the task , Release license
Threads 1: Get a license , Perform tasks
Threads 8: To complete the task , Release license
Threads 2: Get a license , Perform tasks
Threads 5: Get a license , Perform tasks
Threads 2: To complete the task , Release license
Threads 1: To complete the task , Release license
Threads 5: To complete the task , Release license
Threads 9: Get a license , Perform tasks
Threads 6: Get a license , Perform tasks
Threads 10: Get a license , Perform tasks
Threads 6: To complete the task , Release license
Threads 9: To complete the task , Release license
Threads 10: To complete the task , Release license
3. CountDownLatch
- CountDownLatch Translated as the countdown door lock , It can be understood as Counter barrier
- CountDownLatch Use scenario 1 of : Main thread waiting , After multiple sub threads complete the task , Summary and consolidation .
// Main thread waiting , Multiple child threads ( Mission ) After completion , Summary and consolidation
public static void testCountDownLatch() throws InterruptedException {
long start = System.currentTimeMillis();
CountDownLatch countDownLatch = new CountDownLatch(5);
class RUN implements Runnable{
private CountDownLatch latch;
public RUN(CountDownLatch latch){
this.latch = latch;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()+"_ Start execution ");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
//
}
} finally {
System.out.println(Thread.currentThread().getName()+"_ completion of enforcement , Prepare the counter reduce 1 operation ");
latch.countDown();// Use CAS Yes AQS Of volatile state Attributes in -1 operation
}
}
}
for (int i = 0; i < 5; i++) {
new Thread(new RUN(countDownLatch)).start();
}
System.out.println("... The main thread is ready to wait ...");
// Main thread waiting , When counter state==0, Wake up the main thread to execute , The maximum waiting time can be set .
countDownLatch.await();
System.out.println("... The main thread finishes waiting ...");
System.out.println(" It takes time __" + (System.currentTimeMillis()-start));
}
... The main thread is ready to wait ...
Thread-0_ Start execution
Thread-2_ Start execution
Thread-3_ Start execution
Thread-1_ Start execution
Thread-4_ Start execution
Thread-0_ completion of enforcement , Prepare the counter reduce 1 operation
Thread-1_ completion of enforcement , Prepare the counter reduce 1 operation
Thread-4_ completion of enforcement , Prepare the counter reduce 1 operation
Thread-3_ completion of enforcement , Prepare the counter reduce 1 operation
Thread-2_ completion of enforcement , Prepare the counter reduce 1 operation
... The main thread finishes waiting ...
It takes time __2030
- CountDownLatch Use scenario 2 : Multiple threads waiting : Simulate concurrency , The request was blocked as soon as it came in , Let the threads execute together
// Multiple threads waiting : Simulate concurrency , The request was blocked as soon as it came in , Let concurrent threads execute together
public static void testCountDownLatch2() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(1);
class RUN implements Runnable{
private CountDownLatch latch;
public RUN(CountDownLatch latch){
this.latch = latch;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()+"_ Block waiting ");
latch.await();// All requests are blocked here , wait for
System.out.println(Thread.currentThread().getName()+"_ Start execution ");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+"_ completion of enforcement ");
} catch (Exception e){
e.printStackTrace();
}
}
}
for (int i = 0; i < 4; i++) {
new Thread(new RUN(countDownLatch)," Threads "+i).start();
}
TimeUnit.SECONDS.sleep(5); // Main thread sleep Give Way The sub thread requests are all ready
System.out.println("MAIN Threads Make the count minus 1... Wake up all child threads ...");
countDownLatch.countDown();// After the main thread sleeps call countDown() Is the counter minus 1 All child threads will be released
}
Threads 2_ Block waiting
Threads 3_ Block waiting
Threads 0_ Block waiting
Threads 1_ Block waiting
MAIN Threads Make the count minus 1... Wake up all child threads ...
Threads 2_ Start execution
Threads 1_ Start execution
Threads 0_ Start execution
Threads 3_ Start execution
Threads 1_ completion of enforcement
Threads 2_ completion of enforcement
Threads 0_ completion of enforcement
Threads 3_ completion of enforcement
边栏推荐
- File upload and download performance test based on the locust framework
- The child component triggers the defineemits of the parent component: the child component passes values to the parent component
- [upper computer tutorial] Application of integrated stepping motor and Delta PLC (as228t) under CANopen communication
- 8 年产品经验,我总结了这些持续高效研发实践经验 · 研发篇
- B+树索引使用(9)分组、回表、覆盖索引(二十一)
- pomerium
- Algorithm -- continuous sequence (kotlin)
- B+树(3)聚簇索引,二级索引 --mysql从入门到精通(十五)
- We were tossed all night by a Kong performance bug
- Mysql数据目录(2)---表数据结构(二十五)
猜你喜欢

Analysis on the current situation and optimization strategy of customer experience management in banking industry

Kubelet CRI 容器运行时
Exploration on cache design optimization of community like business

How to face scientific and technological unemployment?

File upload and download performance test based on the locust framework

《Kotlin系列》之MVVM架构封装(kotlin+mvvm)

PostgreSQL official website download error

One stroke problem (Chinese postman problem)

如何面对科技性失业?

postgresql官网下载出错
随机推荐
We were tossed all night by a Kong performance bug
HCIP第十二天笔记整理(BGP联邦、选路规则)
B+树(4)联合索引 --mysql从入门到精通(十六)
解决远程主机无法连接mysql数据库的问题
Flutter multi-channel packaging operation
Outline design specification
【C语言学习者必会的题目集锦1】巩固基础,稳步提高
MySQL data directory (1) -- database structure (24)
B+树索引使用(9)分组、回表、覆盖索引(二十一)
如何面对科技性失业?
Reflection, an implementation of automatic repeated call interface
Leetcode 263. ugly number
Mysql数据目录(1)---数据库结构(二十四)
华为机考 ~ 偏移量实现字符串加密
学习pinia 介绍-State-Getters-Actions-Plugins
天津市应急局与驻津央企签署协议深化应急联动机制建设
概要设计说明书
El table implements editable table
基于WebRTC和WebSocket实现的聊天系统
概率论与数理统计