1. 就是共享锁和排他锁(读锁和写锁)
    2. 有的是读线程,有的是写线程
    3. 简单上锁时,效率特别低
    4. 上的是读锁的时候,其他线程可以读,但是不可以写;上的是写锁的时候,其他线程不可以读也不可以写
    5. 这里的锁与数据库里的不会冲突,是两回事;数据库的锁是数据库中的锁,从数据库中读出来到程序中,程序是在内存中的;到内存中了之后,数据库就已经读完了
    6. 不会出现得不到锁,除非cpu只挑读或者写的运行
    7. 与ReentrantLock的Condition很类似
    8. 互斥锁=排他锁
    9. 读的时候不加锁会出现读的时候可以往里面写,会造成数据不一致(脏读)
    1. package com.mashibing.juc.c_020;
    2. import java.util.Random;
    3. import java.util.concurrent.atomic.LongAdder;
    4. import java.util.concurrent.locks.Lock;
    5. import java.util.concurrent.locks.ReadWriteLock;
    6. import java.util.concurrent.locks.ReentrantLock;
    7. import java.util.concurrent.locks.ReentrantReadWriteLock;
    8. public class T10_TestReadWriteLock {
    9. static Lock lock = new ReentrantLock();
    10. private static int value;
    11. static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    12. static Lock readLock = readWriteLock.readLock();
    13. static Lock writeLock = readWriteLock.writeLock();
    14. public static void read(Lock lock) {
    15. try {
    16. lock.lock();
    17. Thread.sleep(1000);
    18. System.out.println("read over!");
    19. //模拟读取操作
    20. } catch (InterruptedException e) {
    21. e.printStackTrace();
    22. } finally {
    23. lock.unlock();
    24. }
    25. }
    26. public static void write(Lock lock, int v) {
    27. try {
    28. lock.lock();
    29. Thread.sleep(1000);
    30. value = v;
    31. System.out.println("write over!");
    32. //模拟写操作
    33. } catch (InterruptedException e) {
    34. e.printStackTrace();
    35. } finally {
    36. lock.unlock();
    37. }
    38. }
    39. public static void main(String[] args) {
    40. //Runnable readR = ()-> read(lock);
    41. Runnable readR = ()-> read(readLock);
    42. //Runnable writeR = ()->write(lock, new Random().nextInt());
    43. Runnable writeR = ()->write(writeLock, new Random().nextInt());
    44. for(int i=0; i<18; i++) new Thread(readR).start();
    45. for(int i=0; i<2; i++) new Thread(writeR).start();
    46. }
    47. }