Skip to content

Commit

Permalink
ReentrantReadWriteLock
Browse files Browse the repository at this point in the history
  • Loading branch information
CPU-Code committed Jul 30, 2021
1 parent 7f764c1 commit c1f43a6
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
2 changes: 2 additions & 0 deletions thread/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@

- [x] [重入锁](src/main/java/com/cpucode/java/aqs/ReentrantDemo.java)
- [x] [ReentrantLock](src/main/java/com/cpucode/java/aqs/AtomicDemo.java)
- [x] [ReentrantReadWriteLock](src/main/java/com/cpucode/java/aqs/RWLock.java)


- [返回文件目录](#文件目录)

Expand Down
65 changes: 65 additions & 0 deletions thread/src/main/java/com/cpucode/java/aqs/RWLock.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.cpucode.java.aqs;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
* @author : cpucode
* @date : 2021/7/30
* @time : 15:22
* @github : https://github.com/CPU-Code
* @csdn : https://blog.csdn.net/qq_44226094
*/
public class RWLock {
static Map<Integer,Object> cacheMap = new HashMap<>();
static ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
static Lock read = rwl.readLock();
static Lock write = rwl.writeLock();

public static final Object get(Integer key) {
System.out.println("开始读取数据");

// 读锁
read.lock();
try {
return cacheMap.get(key);
}finally {
read.unlock();
}

}

public static final Object put(Integer key,Object value){
System.out.println("开始写数据");

write.lock();
try{
return cacheMap.put(key, value);
}finally {
write.unlock();
}
}

public static void main(String[] args) {
for (int i = 0; i < 11; i++) {
int finalI = i;

new Thread(()->{
put(finalI, finalI);
}).start();

new Thread(()->{
get(finalI);
}).start();
}

//读->读是可以共享
//读->写 互斥
//写->写 互斥
//读多写少的场景
}


}

0 comments on commit c1f43a6

Please sign in to comment.