当前位置:网站首页>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 .
边栏推荐
- “山东大学移动互联网开发技术教学网站建设”项目实训日志五
- Reporting Service 2016 自定义身份验证
- 并发编程学习笔记 之 原子操作类AtomicReference、AtomicStampedReference详解
- PHP write a diaper to buy the lowest price in the whole network
- mysql插入百万数据(使用函数和存储过程)
- 钉钉告警脚本
- 重庆大道云行作为软件产业代表受邀参加渝中区重点项目签约仪式
- Changed crying, and finally solved cannot read properties of undefined (reading 'parsecomponent')
- Print out all prime numbers between 1-100
- Flink connector Oracle CDC 实时同步数据到MySQL(Oracle19c)
猜你喜欢

微信内置浏览器禁止缓存的问题

ssm整合

CMD window under Windows connects to MySQL and operates the table

Windos下安装pyspider报错:Please specify --curl-dir=/path/to/built/libcurl解决办法

Laravel service container (Application of context binding)

How to PR an open source composer project

Dao race track is booming. What are the advantages of m-dao?

day02 作业之文件权限

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

与张小姐的春夏秋冬(2)
随机推荐
加密资产熊市之下,PlatoFarm的策略玩法依旧能获得稳定收益
中海油集团,桌面云&网盘存储系统应用案例
Simple optimization of interesting apps for deep learning (suitable for novices)
通过简单的脚本在Linux环境实现Mysql数据库的定时备份(Mysqldump命令备份)
超简单集成HMS ML Kit 人脸检测实现可爱贴纸
Study and research the way of programming
量化开发必掌握的30个知识点【什么是Level-2数据】
MySQL decompressed version windows installation
机器学习让文字识别更简单:Kotlin+MVVM+华为ML Kit
ReportingService WebService Form身份验证
与张小姐的春夏秋冬(5)
Fantom (FTM) prices will soar by 20% in the next few days
Huawei 2020 school recruitment written test programming questions read this article is enough (Part 2)
极致通缩和永动机模型,将推动 PlatoFarm 爆发
马斯克推崇的柏拉图式元宇宙,PlatoFarm早已验证出答案
“山东大学移动互联网开发技术教学网站建设”项目实训日志二
Thinkphp6 pipeline mode pipeline use
How to PR an open source composer project
【go】defer的使用
Crypto giants all in metauniverse, and platofarm may break through