当前位置:网站首页>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
边栏推荐
- B+树挑选索引(2)---mysql从入门到精通(二十三)
- Implementation of SAP ABAP daemon
- 同站攻击(相关域攻击)论文阅读 Can I Take Your Subdomain?Exploring Same-Site Attacks in the Modern Web
- Kubelet CRI 容器运行时
- [typescript] typescript common types (Part 2)
- Sword finger offer (IX): abnormal jumping steps
- One stroke problem (Chinese postman problem)
- 基于Locust框架进行文件上传下载性能测试
- Photoshop (cc2020) unfinished
- Solution 5g technology helps build smart Parks
猜你喜欢

1312_ Apply 7z command for compression and decompression

牛客刷SQL---2

Kubelet CRI 容器运行时

Dimension disaster dimension disaster suspense

Kubernetes apiserver current limiting strategy
![[5gc] what is 5g slice? How does 5g slice work?](/img/8c/52ba57d6a18133e97fa00b6a7cf8bc.png)
[5gc] what is 5g slice? How does 5g slice work?

Ultimate doll 2.0 | cloud native delivery package

基于C#实现的学生考试系统

Photoshop (cc2020) unfinished

Detailed relation extraction model casrel
随机推荐
Photoshop(CC2020)未完
Solution: unable to load the file c:\users\user\appdata\roaming\npm\npx PS1, because running scripts is prohibited on this system.
Can MySQL customize variable parameter storage functions?
Kubernetes apiserver current limiting strategy
Extra(5)—mysql执行计划(五十一)
key&key_ Len & ref & filtered (4) - MySQL execution plan (50)
Outline design specification
Can I take your subdomain? Exploring Same-Site Attacks in the Modern Web
Unicode file parsing methods and existing problems
[flower carving hands-on] interesting and fun music visualization series small project (13) -- organic rod column lamp
8 年产品经验,我总结了这些持续高效研发实践经验 · 研发篇
解决方案丨5G技术助力搭建智慧园区
同花顺开的账户安全吗?
深度学习3D人体姿态估计国内外研究现状及痛点
Hcip day 12 notes sorting (BGP Federation, routing rules)
We were tossed all night by a Kong performance bug
基于Locust框架进行文件上传下载性能测试
Unity中序列化类为json格式
A college archives management system based on asp.net
Sword finger offer (x): rectangular coverage