ReentrantReadWriteLock 读写锁

 1 package juc;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 import java.util.concurrent.TimeUnit;
 6 import java.util.concurrent.locks.ReadWriteLock;
 7 import java.util.concurrent.locks.ReentrantReadWriteLock;
 8 
 9 /**
10  * @author : 雪飞oubai
11  * @date : 2020/3/27 10:36
12  * 多个线程同时读一个资源类没有任何问题,所以为了满足并发量,
13  * 读取共享资源应该可以同时进行。但是,如果如果有一个线程想去
14  * 写共享资源来,就不应该在有其他线程可以对该资源进行读或写。
15  * 总结:
16  * 读-读能共存
17  * 读-写不能共存
18  * 写-写不能共存
19  */
20 public class ReadWriteLockDemo {
21     public static void main(String[] args) {
22         MyCache myCache = new MyCache();
23         for (int i = 0; i < 5; i++) {
24             final int finalI = i;
25             new Thread(() -> {
26                 myCache.put(finalI + "", finalI + "");
27             }, String.valueOf(i)).start();
28         }
29         for (int i = 0; i < 5; i++) {
30             final int finalI = i;
31             new Thread(() -> {
32                 myCache.get(finalI + "");
33             }, String.valueOf(i)).start();
34         }
35     }
36 }
37 
38 class MyCache {
39     private volatile Map map = new HashMap();
40 
41     private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
42 
43     public void put(String key, String value) {
44         try {
45             readWriteLock.writeLock().lock();
46             System.out.println(Thread.currentThread().getName() + "\t写入数据");
47             try {
48                 TimeUnit.MILLISECONDS.sleep(300);
49             } catch (InterruptedException e) {
50                 e.printStackTrace();
51             }
52             map.put(key, value);
53             System.out.println(Thread.currentThread().getName() + "\t写入完成");
54         } catch (Exception e) {
55             e.printStackTrace();
56         } finally {
57             readWriteLock.writeLock().unlock();
58         }
59     }
60 
61     public void get(String key) {
62         try {
63             readWriteLock.readLock().lock();
64             System.out.println(Thread.currentThread().getName() + "\t读取数据");
65             try {
66                 TimeUnit.MILLISECONDS.sleep(300);
67             } catch (InterruptedException e) {
68                 e.printStackTrace();
69             }
70             Object result = map.get(key);
71             System.out.println(Thread.currentThread().getName() + "\t读取完成" + result);
72         } catch (Exception e) {
73             e.printStackTrace();
74         } finally {
75             readWriteLock.readLock().unlock();
76         }
77     }
78 }

ReentrantReadWriteLock 读写锁_第1张图片

 

你可能感兴趣的:(ReentrantReadWriteLock 读写锁)