当前位置:网站首页>Read / write lock example
Read / write lock example
2022-06-30 04:22:00 【No bug program yuan】
There is no problem with multiple threads reading a resource class at the same time , So in order to meet the concurrency , Reading shared resources should be possible at the same time . If a thread wants to write a shared resource , No other thread should be able to read or write a summary of the resource :
read - Reading can co-exist
read - Writing cannot coexist
Write - Writing cannot coexist
Write operations : atom + Monopoly , The whole process must be a complete unity , The middle must not be divided , Be interrupted
Write can only be one thread , Read can be read by multiple threads
Original way , The write operation will be interrupted :
class MyDataMap{
private volatile Map<String,Object>map=new HashMap<>();
public void put(String key,Object value) {
try {
System.out.println(Thread.currentThread().getName()+" Are written to the :"+key);
Thread.sleep(300);
map.put(key,value);
System.out.println(Thread.currentThread().getName()+" Write completion :"+key);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void get(String key){
System.out.println(Thread.currentThread().getName()+" Reading :"+key);
try {
Thread.sleep(300);
Object result = map.get(key);
System.out.println(Thread.currentThread().getName()+" Read complete :"+result);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
MyDataMap myData=new MyDataMap();
for (int i=1;i<=5;i++){
final int temp=i;
new Thread(()->{
myData.put(temp+"","dd"+temp);
},String.valueOf(i)).start();
}
for (int i=1;i<=5;i++){
final int temp=i;
new Thread(()->{
myData.get(temp+"");
},String.valueOf(i)).start();
}
}
} The result is :
1 Are written to the :1
2 Are written to the :2
3 Are written to the :3
4 Are written to the :4
5 Are written to the :5
1 Reading :1
2 Reading :2
3 Reading :3
4 Reading :4
5 Reading :5
1 Read complete :null
2 Read complete :null
3 Read complete :null
4 Read complete :null
5 Read complete :null
1 Write completion :1
2 Write completion :2
3 Write completion :3
4 Write completion :4
5 Write completion :5The write operation is not interrupted , You can read the sample code through multiple threads :
class MyData{
private volatile Map<String,Object>map=new HashMap<>();
private ReentrantReadWriteLock rwLock=new ReentrantReadWriteLock();
public void put(String key,Object value) {
try {
rwLock.writeLock().lock();
System.out.println(Thread.currentThread().getName()+" Are written to the :"+key);
Thread.sleep(300);
map.put(key,value);
System.out.println(Thread.currentThread().getName()+" Write completion :"+key);
} catch (InterruptedException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}finally {
rwLock.writeLock().unlock();
}
}
public void get(String key){
rwLock.readLock().lock();
System.out.println(Thread.currentThread().getName()+" Reading :"+key);
try {
Thread.sleep(300);
Object result = map.get(key);
System.out.println(Thread.currentThread().getName()+" Read complete :"+result);
} catch (InterruptedException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
finally {
rwLock.readLock().unlock();
}
}
public static void main(String[] args) {
MyData myData=new MyData();
for (int i=1;i<=5;i++){
final int temp=i;
new Thread(()->{
myData.put(temp+"","dd"+temp);
},String.valueOf(i)).start();
}
for (int i=1;i<=5;i++){
final int temp=i;
new Thread(()->{
myData.get(temp+"");
},String.valueOf(i)).start();
}
}
}Execution results : Other threads cannot interrupt when writing
2 Are written to the :2
2 Write completion :2
1 Are written to the :1
1 Write completion :1
3 Are written to the :3
3 Write completion :3
4 Are written to the :4
4 Write completion :4
5 Are written to the :5
5 Write completion :5
1 Reading :1
4 Reading :4
3 Reading :3
5 Reading :5
2 Reading :2
5 Read complete :dd5
2 Read complete :dd2
3 Read complete :dd3
4 Read complete :dd4
1 Read complete :dd1Semaphore: Semaphore , A mutually exclusive use for multiple shared resources , Another control for the number of concurrent threads .
void acquire(): Get a permission from this semaphore , The thread is blocked until a permission is provided , Otherwise, the thread is interrupted .
void release(): Release a license , Return it to semaphore .
Only three parking spaces , One car will occupy one parking space , Take a car and release a parking space
Example :
public static void main(String[] args) {
Semaphore semaphore=new Semaphore(3);
for (int i = 1; i <=6 ; i++) {
new Thread(()->{
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"\t Grab the parking space ");
Thread.sleep(3);
System.out.println(Thread.currentThread().getName()+"\t Parking 3 Leave the parking space in seconds ");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
},String.valueOf(i)).start();
}
}边栏推荐
- Myrpc version 4
- SQL append field
- JS file block to Base64 text
- 各位大佬,flink 1.13.6,mysql-cdc2.2.0,抽取上来的datetime(6)类
- 第九天 脚本與資源管理
- Five methods to clear floating and their advantages and disadvantages
- 2021-07-14
- Educoder group purchase suspension box page production
- Troubleshoot abnormal video playback problems in public network deployment based on Haikang ehomedemo tool
- The new paradigm of AI landing is "hidden" in the next major upgrade of software infrastructure
猜你喜欢

尝试链接数据库时出现链接超时报错,如何解决?

Day 10 data saving and loading

How the FortiGate firewall rejects a port by using the local in policy policy

el-upload上傳文件(手動上傳,自動上傳,上傳進度)

Interview topic of MySQL

OneNote software

El upload Upload file (Manual upload, Automatic upload, upload progress)

With the deep integration of cloud platform, the "Xueba" objectscale in the object storage industry is coming
![[Thesis reading | deep reading] dane:deep attributed network embedding](/img/c7/60f36c2748b8cd7544b7ef14dc309e.png)
[Thesis reading | deep reading] dane:deep attributed network embedding

(03). Net Maui actual combat basic control
随机推荐
internship:接口案例实现
Technology sharing | broadcast function design in integrated dispatching
oslo_ config. cfg. ConfigFileParseError: Failed to parse /etc/glance/glance-api. Conf: a solution to errors
Iterator of JS
Cloud native -- websocket of Web real-time communication technology
基于servlet+jsp+mysql实现的工资管理系统【源码+数据库】
JS reflect
Everyone, Flink 1.13.6, mysql-cdc2.2.0, the datetime (6) class extracted
【WEBRTC】ADM: rtc_ include_ internal_ audio_ Device triggers RTC_ Dcheck (ADM) assertion
Machine learning notes
El upload upload file (manual upload, automatic upload, upload progress)
FortiGate configures multiple server IPS as link monitor monitoring objects on the same interface
Idea grey screen problem
Unity 在編輯器中輸入字符串時,轉義字符的輸入
JS inheritance
Myrpc version 2
I spent three years in a big factory outsourcing, which subverted my understanding!
Junior students summarize JS basic interview questions
With the deep integration of cloud platform, the "Xueba" objectscale in the object storage industry is coming
管道实现进程间通信之命名管道