当前位置:网站首页>Common classes under JUC package
Common classes under JUC package
2022-07-21 05:26:00 【TPH-BETTER】
JUC Common classes under the package
from https://blog.csdn.net/m0_59140023/article/details/124515730
Preface
java.util.concurrent The class under is called JUC class ,JUC The following typical classes are :
- ReentrantLock : Reentrant lock ;
* Semaphore : Semaphore ;
* CountDownLatch : Counter ;
* CyclicBarrier : Circulation barrier .
1、ReentrantLock
Reentrant mutexes . and synchronized Similar location , Are used to achieve mutually exclusive effects , Thread safe .
ReentrantLock Usage of :
- lock(): Lock , If you can't get the lock, you'll die and wait ;
- trylock( Timeout time ): Lock , If the lock cannot be acquired , Give up locking after waiting for a certain time ;
- unlock(): Unlock .
ReentrantLock and synchronized The difference between :
- synchronized It's a keyword , yes JVM Internally realized ( The probability is based on C++ Realization ). ReentrantLock Is a class of the standard library , stay JVM Implemented outside ( be based on Java Realization ).
- synchronized There is no need to manually release the lock when using . ReentrantLock Manual release is required during use . More flexible to use , But it's also easy to miss unlock.
- synchronized When the lock application fails , Will die, etc . ReentrantLock Can pass trylock Wait a while and give up .
- synchronized Fair lock , ReentrantLock Default is unfair lock . You can pass in a through the construction method true Open fair lock mode .
- More powerful wake-up mechanism . synchronized It's through Object Of wait / notify Realize the wait - Wake up the . Each wake-up is a random waiting thread . ReentrantLock collocation Condition Class implementation wait - Wake up the , It can more precisely control the wake-up of a specified thread .
How to choose which lock to use ?
- When lock competition is not fierce , Use synchronized, More efficient , Automatic release is more convenient .
- When lock competition is fierce , Use ReentrantLock, collocation trylock More flexible control of locking behavior , Instead of waiting .
- If you need to use a fair lock , Use ReentrantLock.
2、Semaphore
Semaphore , Used to represent “ Number of available resources ”, It's essentially a counter . This class is used to control the number of semaphores , Number of passed in during construction . The total number is the number of concurrent control .
If so 5, Use... Before program execution acquire() Method to obtain the signal , Then the available signal becomes 4, After the program is executed, pass release() Method returns the semaphore , The available signal becomes 5. If available, the signal is 0,acquire It's going to cause a blockage , wait for release Release the signal .acquire and release Methods can not be used in the same thread .
public class SemaphoreDemo {
// Create semaphores
static Semaphore semaphore = new Semaphore(2);
public static void main(String[] args) {
// Create a thread pool with a fixed number of threads
ExecutorService service = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100 * i);
} catch (InterruptedException e) {
e.printStackTrace();
}
service.submit(() -> {
Thread currThread = Thread.currentThread();
System.out.println(" Enter thread :" + currThread.getName());
try {
// Get token
semaphore.acquire();
System.out.println(currThread.getName() + " Get the token :" + LocalDateTime.now());
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(currThread.getName() + " release token :" + LocalDateTime.now());
semaphore.release();
}
});
}
service.shutdown();
}
}
The number of semaphores is 2, Threads 1 And thread 2 Get the token first , The semaphore is 0, Until the thread 1 Released the token , Threads 3 To get a token , Threads 2 Released the token , Threads 4 To get the token .
3、CountDownLatch
Counter , Wait at the same time N End of task execution . It's like a running race ,10 Players are in place in turn , The whistle went off at the same time ; All the players passed the finish line , To announce the results .
Sample code : Running races
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
// Create calculator
CountDownLatch countDownLatch = new CountDownLatch(5);
// Creating a thread pool
ExecutorService service = Executors.newFixedThreadPool(5);
// Create a new thread to perform the task
for (int i = 1; i <= 5; i++) {
service.submit(() -> {
Thread currThread = Thread.currentThread();
System.out.println(currThread.getName() + " Start running ");
int runTime = new Random().nextInt(5) + 1;
try {
TimeUnit.SECONDS.sleep(runTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(currThread.getName() + " Reach the end point , when :" + runTime);
countDownLatch.countDown();
});
}
countDownLatch.await();
System.out.println(" The result of the game was announced !");
}
}
Running results :
4、 CyclicBarrier
Circulation barrier , It can work with multiple threads , Let multiple threads wait before this barrier , Until all threads have reached this barrier , Then perform the following operations together . Suppose each thread has one await, Any thread runs to await Method is blocked , Until the last thread runs to await At the same time .
public class CyclicBarrierDemo {
public static void main(String[] args) {
// Circulation barrier
CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> System.out.println(" The counter for 5 了 "));
// Creating a thread pool
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
int finalI = i;
service.submit(() -> {
Thread currThread = Thread.currentThread();
System.out.println(" Execute thread :" + currThread);
try {
Thread.sleep(500 * finalI);
cyclicBarrier.await(); // Perform blocking wait ( Counter +1, Until the cycle counter is 5 Execute the following code when you need to )
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println(" Thread execution complete !" + currThread.getName());
});
}
}
}
Running results :
The barrier set is 5, Each thread executes to await Method will block and wait , Until the counter is 0 when , Execute the following code (5 Threads executing at the same time ).
Two classes that look a little bit like , All in java.util.concurrent Next , Can be used to indicate that the code runs to a certain point , both of them
The difference is that :
1 、 CyclicBarrier After a thread of runs to a point , The thread stops running , Until all the threads have reached this
A little bit , All threads are rerun ; CountDownLatch It is not , After a thread runs to a certain point , Just give a number
value -1 nothing more , The thread continues to run
2 、 CyclicBarrier To invoke multiple threads , CountDownLatch Only one thread can be invoked
3 、 CyclicBarrier reusable , CountDownLatch Not reusable , The count is 0 The CountDownLatch It can no longer be used
了
边栏推荐
猜你喜欢
How much money do young people who do 3D, digital people and metauniverse make?
[Verilog digital system design (Xia Yuwen) -- basic knowledge of Verilog 2]
【HBuilder运行到MuMu模拟器无法安装基座的问题,一直卡在安装基座...】
ASP.NET Core 使用Autofac
Flink 的学习笔记
pytest + allure 结合使用展示图表结果(3)
go runtime 包
Iptables防火墙实验
Shell script learning
【el-upload实现一个修改头像的功能】
随机推荐
General packaging technology of GRE and mGRE
Nuscenes数据集总结
研究一下 JSON.parse(JSON.stringify(obj))
每日三题 7.15
enable_ If and partial specialization
小程序毕设作品之微信运动场地预约小程序毕业设计(6)开题答辩PPT
Program environment and pretreatment
物理实验模拟
UML图系列之序列图
pytest + allure 结合使用展示图表结果(3)
程序媛发文感慨失业,引来各行业程序猿安慰,笑喷在评论区
About the processing of single cell TPM and count data part1
localtime()
Fluent print widget level list
How much money do young people who do 3D, digital people and metauniverse make?
VS2017修改默认包含目录、库目录
Loop filtering using SSIM based CNN
Addition, deletion, query and modification of MySQL [advanced]
Go runtime package
[recursion & divide and conquer] compressed transformation (using interval tree and dichotomy, recursively count the number types in the specified interval)