独占锁(写锁)一次只能被一个线程占有
    共享锁(读锁)多个线程可以同时占有

    1. public class LockTest {
    2. public static void main(String[] args) throws InterruptedException {
    3. CacheDemo cacheDemo = new CacheDemo();
    4. // 写入
    5. for (int i = 0; i < 5; i++) {
    6. final int temp = i;
    7. new Thread(()->{
    8. cacheDemo.put(temp + "", temp + "");
    9. }, String.valueOf(i)).start();
    10. }
    11. // 读取
    12. for (int i = 0; i < 5; i++) {
    13. final int temp = i;
    14. new Thread(()->{
    15. cacheDemo.get(temp + "");
    16. }, String.valueOf(i)).start();
    17. }
    18. }
    19. }
    20. class CacheDemo {
    21. private volatile Map<String, Object> map = new HashMap<>();
    22. // 读写锁
    23. private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    24. public void put(String key, Object value) {
    25. // 加写锁
    26. readWriteLock.writeLock().lock();
    27. try {
    28. System.out.println("写入:" + Thread.currentThread().getName());
    29. map.put(key, value);
    30. System.out.println("写完:" + Thread.currentThread().getName());
    31. } catch (Exception e) {
    32. e.printStackTrace();
    33. } finally {
    34. readWriteLock.writeLock().unlock();
    35. }
    36. }
    37. public void get(String key) {
    38. readWriteLock.readLock().lock();
    39. try {
    40. System.out.println("读取:" + Thread.currentThread().getName());
    41. map.get(key);
    42. System.out.println("读完:" + Thread.currentThread().getName());
    43. } catch (Exception e) {
    44. e.printStackTrace();
    45. } finally {
    46. readWriteLock.readLock().unlock();
    47. }
    48. }
    49. }