当前位置:网站首页>Semaphore (semaphore) for learning notes of concurrent programming
Semaphore (semaphore) for learning notes of concurrent programming
2022-07-29 05:56:00 【People with different feelings】
1、 Concept
Semaphore( Semaphore ) Is a thread synchronization tool , It is mainly used in scenarios that allow multiple threads to operate in parallel on shared resources at one time . Usually , Use Semaphore The process of is actually the process of multiple threads obtaining the license to access shared resources .
Semaphore Internal logic :
- If at this time Semaphore The internal counter is greater than zero , Then the thread will be able to obtain licenses less than the number of counters , And it also causes Semaphore The internal counter reduces the number of licenses issued .
- If at this time Semaphore The internal counter is equal to 0, That is, there is no license available , Then the current thread may be blocked ( Use tryAcquire Method does not block ).
- When the thread no longer uses the license , It needs to be released immediately for use by other threads , Therefore, it is suggested to write the acquisition and release of the license in try…finally In the block .
2、Semaphore Examples of use
The scenario of the largest number of people is simulated here , When the number of people reaches the upper limit, close , Subsequent threads cannot enter , When a semaphore is released , Subsequent threads can continue to enter .
public class SemaphoreTest {
public static void main(String[] args) {
final LoginService loginService = new LoginService(5);
for (int i=0;i<10;i++){
Thread thread = new Thread(()->{
if(loginService.login()){
try {
// Simulate travel time
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
System.out.println(Thread.currentThread().getName() + ", Start playing !");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
loginService.logout();
}
}else{
System.out.println(Thread.currentThread().getName() + " People with , Go home and sleep !");
}
});
thread.start();
}
}
private static class LoginService{
private final Semaphore semaphore;
public LoginService(int maxUser){
this.semaphore = new Semaphore(maxUser,true);
}
public boolean login(){
if(semaphore.tryAcquire()){
System.out.println(Thread.currentThread().getName() + ", Success in entering the park !");
return true;
}
return false;
}
public void logout(){
semaphore.release();
System.out.println(Thread.currentThread().getName() + ", Out of the garden !");
}
}
}
Thread-0, Success in entering the park !
Thread-1, Success in entering the park !
Thread-2, Success in entering the park !
Thread-3, Success in entering the park !
Thread-4, Success in entering the park !
Thread-5 People with , Go home and sleep !
Thread-6 People with , Go home and sleep !
Thread-3, Start playing !
Thread-3, Out of the garden !
Thread-7, Success in entering the park !
Thread-9 People with , Go home and sleep !
Thread-8 People with , Go home and sleep !
Thread-0, Start playing !
Thread-0, Out of the garden !
Thread-1, Start playing !
Thread-1, Out of the garden !
Thread-7, Start playing !
Thread-7, Out of the garden !
Thread-4, Start playing !
Thread-4, Out of the garden !
Thread-2, Start playing !
Thread-2, Out of the garden !
In the example above , Threads “Thread-7” Wait until there are resources , You can get entry qualification again .
release Method : stay Semaphore In design , Enforcement is not mandatory release The thread of operation must be executed acquire Thread can , Instead, developers need to have corresponding programming constraints to ensure Semaphore The correct use of , This may cause the thread that does not get the semaphore to call release Method , Thus causing the wrong release of semaphore . Examples of errors are as follows , Originally, the main thread should not get semaphores , But it's actually because t2 Thread interrupt , Yes finally Of release Method , Caused the wrong release of semaphore .
public class Semaphore2Test {
public static void main(String[] args) throws InterruptedException {
// Defining semaphores
final Semaphore semaphore = new Semaphore(1,true);
Thread t1 = new Thread(()->{
try{
semaphore.acquire();
System.out.println("t1 Get resources !");
TimeUnit.HOURS.sleep(1);
}catch (Exception e){
System.out.println("t1 The current thread is interrupted !");
}finally {
semaphore.release();
}
});
Thread t2 = new Thread(()->{
try{
semaphore.acquire();
System.out.println("t2 Get resources !");
}catch (Exception e){
System.out.println("t2 The current thread is interrupted !");
}finally {
semaphore.release();
}
});
t1.start();
TimeUnit.SECONDS.sleep(2);
t2.start();
TimeUnit.SECONDS.sleep(2);
t2.interrupt();
semaphore.acquire();
System.out.println(" The main thread obtains resource access permission !");
}
}
3、Semaphore Common methods
1、 Constructors
There are two constructors . among , The so-called fair semaphore is that the order in which locks are obtained is related to the order in which threads are started , But it does not represent. 100% To get semaphores , It can be guaranteed only in probability . The non fair semaphore is irrelevant .
- public Semaphore(int permits): Definition Semaphore Specify the number of licenses , And specify an unfair synchronizer , therefore new Semaphore(n) It's actually the same thing as new Semaphore(n,false) Of .
- public Semaphore(int permits, boolean fair): Definition Semaphore Specify the number of licenses while giving an unfair or fair synchronizer .
2、tryAcquire Method
tryAcquire Method try to Semaphore Get a license , If the number of licenses at this time is less than the number of applications , Then the corresponding thread will immediately return , The result is false Indicates that the application failed ,tryAcquire It includes the following :
- tryAcquire(): Try to get Semaphore The license for , This method will only apply to Semaphore Apply for a license , stay Semaphore The number of internal available licenses is greater than or equal to 1 Under the circumstances , The license will be successful , Otherwise, obtaining the license will fail , And the return result is false.
- boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException: The method and tryAcquire The parameterless method is similar , Also try to get a license , But the timeout parameter is added . If no license is available within the timeout , Then the thread will enter the blocking state , Until the timeout period is reached or a certificate is available within the timeout period ( Certificates released by other threads ), Or the thread in the block is interrupted by other threads .
- boolean tryAcquire(int permits): In the use of parameterless tryAcquire Time will only go to Semaphore Try to get a license , But this method will Semaphore Try to acquire a specified number of licenses .
- boolean tryAcquire(int permits, long timeout, TimeUnit unit): This method is similar to the second method , However, it can specify the parameters of the number of licenses to try to obtain
3、acquire Method
acquire The method is also to Semaphore Get a license , But this method is more paranoid , If you don't get it, you will wait ( Stuck in a jam ), But it can be interrupted by other threads ,Semaphore For us acquire Two overloaded forms of methods :
- void acquire(): This method will report to Semaphore Get a license , If you can't get it, you will wait , until Semaphore Until a license is available , Or interrupted by another thread . Of course , If a license is available, it will be returned immediately .
- void acquire(int permits): This method will report to Semaphore Obtain the specified number of licenses , If you can't get it, you will wait , until Semaphore Until a corresponding number of licenses are available , Or interrupted by another thread . Again , If available permits Licenses will be returned immediately .
4、acquireUninterruptibly Method
and acquire Methods compared , Not interrupted by other threads .
- void acquireUninterruptibly(): This method will report to Semaphore Get a license , If you can't get it, you will wait , At the same time, any interruption to the thread will be ignored , until Semaphore Until a license is available . Of course , If a license is available, it will be returned immediately .
- void acquireUninterruptibly(int permits): This method will report to Semaphore Obtain the specified number of licenses , If you can't get it, you will wait , At the same time, any interruption to the thread will be ignored , until Semaphore Until a license is available , Or interrupted by another thread . Again , If available permits Licenses will be returned immediately .
5、release Method
release Methods need to be used correctly , Avoid the situations mentioned above .
- void release(): Release a license , And in Semaphore Internal , The counter of available licenses will be incremented , Indicates that a new license is currently available .
- void release(int permits): Release the specified amount (permits) The license for , And in Semaphore Inside , The counter of available licenses will increase permits individual , It indicates that there are permits Licenses can be used .
边栏推荐
- 【数据库】数据库课程设计一一疫苗接种数据库
- Extreme deflation and perpetual motion machine model will promote the outbreak of platofarm
- Fantom (FTM) prices will soar by 20% in the next few days
- 性能对比|FASS iSCSI vs NVMe/TCP
- The Platonic metauniverse advocated by musk has long been verified by platofarm
- Plato Farm有望通过Elephant Swap,进一步向外拓展生态
- Changed crying, and finally solved cannot read properties of undefined (reading 'parsecomponent')
- 手撕ORM 框架(泛型+注解+反射)
- PHP write a diaper to buy the lowest price in the whole network
- Under the bear market of encrypted assets, platofarm's strategy can still obtain stable income
猜你喜欢

SSM integration

Plato farm is expected to further expand its ecosystem through elephant swap

超简单集成HMS ML Kit 实现parental control

nacos外置数据库的配置与使用

Laravel swagger add access password

Research and implementation of flash loan DAPP

How can Plato obtain premium income through elephant swap in a bear market?

Reporting Service 2016 自定义身份验证

识变!应变!求变!

Thinkphp6 output QR code image format to solve the conflict with debug
随机推荐
量化开发必掌握的30个知识点【什么是分笔逐笔数据】?
并发编程学习笔记 之 Lock锁及其实现类ReentrantLock、ReentrantReadWriteLock和StampedLock的基本用法
30 knowledge points that must be mastered in quantitative development [what is individual data]?
全闪分布式,如何深度性能POC?
MOVE PROTOCOL全球健康宣言,将健康运动进行到底
How to make interesting apps for deep learning with zero code (suitable for novices)
Madonna "hellent" bought $1.3 million NFT boring ape, which is now considered too expensive
Laravel service container (inheritance and events)
Reporting Services- Web Service
Synchronous development with open source projects & codereview & pull request & Fork how to pull the original warehouse
Idea using JDBC to connect mysql database personal detailed tutorial
DeFi 2.0的LaaS协议,重振DeFi赛道发展的关键
马斯克推崇的柏拉图式元宇宙,PlatoFarm早已验证出答案
30 knowledge points that must be mastered in quantitative development [what is level-2 data]
裸金属云FASS高性能弹性块存储解决方案
Most PHP programmers don't understand how to deploy safe code
How does PHP generate QR code?
Elastic box flex
我的理想工作,码农的绝对自由支配才是最重要的——未来创业的追求
Thinkphp6 pipeline mode pipeline use