• Read/write locks are actually implemented by shared locks and exclusive locks. Read/write locks allow multiple read threads to read data at the same time. The read lock and write lock are mutually exclusive, and only one write lock can be acquired by the writer thread at a time to write data. In this case, data cannot be read. As long as it is applicable to the application with few data update scenarios, the system efficiency can be improved.
public class TestReentrantReadWriteLock {

    static ReadWriteLock rwl = new ReentrantReadWriteLock();
    static Lock writeLock = rwl.readLock();
    static Lock readLock = rwl.writeLock();
    private static int value = 0;

    public static void read(Lock l) {
        try {
            l.lock();
            Thread.sleep(1000);
            System.out.println("read over! value: " + value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            l.unlock();
        }
    }

    public static void write(Lock l) {
        try {
            l.lock();
            Thread.sleep(1000);
            value += 1;
            System.out.println("write over! " + value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            l.unlock();
        }
    }

    public static void main(String[] args) {
        for(int i=0; i<8; i++) {
            new Thread(() -> {
                write(readLock);
            }).start();
        }
        for(int j=0; j<10; j++) {
            new Thread(()->{
                read(writeLock); }).start(); }}}Copy the code