JUC-07-读写锁

JUC-07-读写锁

1. 简介

mark

读:可以被多个线程同时读

写:只能有一个线程去写

2. 代码测试

2.1 未加锁

  1. 自定义缓存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class MyCache{
private volatile Map<String,Object> map = new HashMap<String, Object>();

// 存 : 写
public void put(String key, Object value){
System.out.println(Thread.currentThread().getName()+"写入"+key);
map.put(key,value);
System.out.println(Thread.currentThread().getName()+"写入OK");
}

// 取 : 写
public void get(String key){
System.out.println(Thread.currentThread().getName()+"读取"+key);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName()+"读取OK");
}
}
  1. 多线程操作缓存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class ReadWriteLockDemo {

/*
自定义缓存
*/
public static void main(String[] args) {
MyCache myCache = new MyCache();

// 写入
for (int i = 0; i <= 5;i++){
final int temp = i;
new Thread(()->{
myCache.put(temp+"",temp+"");
},String.valueOf(i)).start();
}

// 读取
for (int i = 0; i <= 5;i++){
final int temp = i;
new Thread(()->{
myCache.get(temp+"");
},String.valueOf(i)).start();
}
}

}

这种情况是有问题的:会有同时写入存在的情况

mark

2.2 加锁

加入一把读写锁

  1. 自定义缓存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class MyCache2{
private volatile Map<String,Object> map = new HashMap<String, Object>();
// 读写锁:更加细粒度的控制
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

// 存 : 写(只希望一个线程 去写)
public void put(String key, Object value){
// 写锁
readWriteLock.writeLock().lock();

try {
System.out.println(Thread.currentThread().getName()+"写入"+key);
map.put(key,value);
System.out.println(Thread.currentThread().getName()+"写入OK");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.writeLock().unlock();
}
}

// 取 : 写
public void get(String key){

// 读锁
readWriteLock.readLock().lock();

try {
System.out.println(Thread.currentThread().getName()+"读取"+key);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName()+"读取OK");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.readLock().unlock();
}
}
}
  1. 多线程操作缓存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class ReadWriteLockDemo {

/*
自定义缓存
*/
public static void main(String[] args) {
MyCache2 myCache2 = new MyCache2();

// 写入
for (int i = 0; i <= 5;i++){
final int temp = i;
new Thread(()->{
myCache2.put(temp+"",temp+"");
},String.valueOf(i)).start();
}

// 读取
for (int i = 0; i <= 5;i++){
final int temp = i;
new Thread(()->{
myCache2.get(temp+"");
},String.valueOf(i)).start();
}
}

}

结果如下:问题解决!!!

mark

3.小结

  • 读-读:可以共存
  • 读-写: 不能共存
  • 写-写: 不能共存

独占锁:一次只能被一个线程占有(写锁)

共享锁:多个线程可以同时占有(读锁)

打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信