当前位置:网站首页>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 .
边栏推荐
- Xsan is highly available - xdfs and San are integrated with new vitality
- 裸金属云FASS高性能弹性块存储解决方案
- Thinkphp6 output QR code image format to solve the conflict with debug
- Okaleido Tiger 7.27日登录Binance NFT,首轮已获不俗成绩
- 华为2020校招笔试编程题 看这篇就够了(下)
- iSCSI vs iSER vs NVMe-TCP vs NVMe-RDMA
- 识变!应变!求变!
- Huawei 2020 school recruitment written test programming questions read this article is enough (Part 2)
- Thinkphp6 pipeline mode pipeline use
- Shanzhai coin Shib has a US $548.6 million stake in eth whale's portfolio - traders should be on guard
猜你喜欢

华为2020校招笔试编程题 看这篇就够了(下)

马斯克推崇的柏拉图式元宇宙,PlatoFarm早已验证出答案

mysql插入百万数据(使用函数和存储过程)

C# 连接 SharepointOnline WebService

“山东大学移动互联网开发技术教学网站建设”项目实训日志四

一文读懂Move2Earn项目——MOVE

Training log 7 of the project "construction of Shandong University mobile Internet development technology teaching website"

"Shandong University mobile Internet development technology teaching website construction" project training log V

Gluster集群管理小分析

熊市慢慢,Bit.Store提供稳定Staking产品助你穿越牛熊
随机推荐
Mobile terminal -flex item attribute
Move protocol global health declaration, carry out the health campaign to the end
Most PHP programmers don't understand how to deploy safe code
How to survive in the bear market of encryption market?
并发编程学习笔记 之 ReentrantLock实现原理的探究
Strategic cooperation with many institutions shows the strength of the leading company of platofarm yuancosmos
DeFi 2.0的LaaS协议,重振DeFi赛道发展的关键
超简单集成HMS ML Kit 人脸检测实现可爱贴纸
Synchronous development with open source projects & codereview & pull request & Fork how to pull the original warehouse
重庆大道云行作为软件产业代表受邀参加渝中区重点项目签约仪式
极致通缩和永动机模型,将推动 PlatoFarm 爆发
Crypto giants all in metauniverse, and platofarm may break through
Reporting Services- Web Service
Starfish OS:以现实为纽带,打造元宇宙新范式
datax安装
性能对比|FASS iSCSI vs NVMe/TCP
在uni-app项目中,如何实现微信小程序openid的获取
Fantom (FTM) prices will soar by 20% in the next few days
ssm整合
与张小姐的春夏秋冬(4)