Java多线程-读写锁ReentrantReadWriteLock类

共享锁 与 排他锁

ReentrantReadWriteLock类有两个锁,一个是读操作相关的锁,即共享锁。另一个是写操作相关的锁,即排他锁。

也就是多个读锁之间不互斥,读锁与写锁互斥,写锁与写锁互斥。

 

读锁与读锁共享

示例:

public class Test {
    public static void main(String[] args) {
        Service service = new Service();
        new Thread(() -> service.read(), "A").start();
        new Thread(() -> service.read(), "B").start();
    }

    static class Service {
        private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        public void read() {
            lock.readLock().lock();
            try {
                System.out.println("线程" + Thread.currentThread().getName() + "获得读锁 " + System.currentTimeMillis());
                Thread.sleep(2000);
                System.out.println("线程" + Thread.currentThread().getName() + "读取完毕");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.readLock().unlock();
            }

        }
    }
}

运行结果如下:

 

 

读锁与写锁互斥

示例:

public class Test {
    public static void main(String[] args) {
        Service service = new Service();
        new Thread(() -> service.read(), "A").start();
        new Thread(() -> service.read(), "B").start();
    }

    static class Service {
        private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        public void read() {
            lock.writeLock().lock();
            try {
                System.out.println("线程" + Thread.currentThread().getName() + "获得写锁 " + System.currentTimeMillis());
                Thread.sleep(2000);
                System.out.println("线程" + Thread.currentThread().getName() + "写完毕");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.writeLock().unlock();
            }

        }
    }
}

运行结果如下:

 

posted @ 2020-03-25 11:47  lkc9  阅读(166)  评论(0编辑  收藏  举报