读写锁,ReadWriteLock

·  阅读 86
  • 读写锁其实是由共享锁和排他锁实现。读写锁即多个读线程可共享一把读锁,允许多个读线程同时读数据,读锁和写锁互斥,且同一时刻只允许写线程拿到一把写锁来写数据,此时不能读数据。只要适用于数据更新场景较少的应用,提高系统的效率。
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();
        }
    }

}

复制代码
分类:
阅读
标签:
分类:
阅读
标签: