首页 > 其他 > 详细

7.ReadWriteLock的使用以及源码解读

时间:2021-07-18 13:03:37      阅读:14      评论:0      收藏:0      [点我收藏+]

1.读读共享

public static void main(String[] args) {
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    for (int i = 0; i < 5; i++) {
      new Thread(()->{
        Lock lock = readWriteLock.readLock();
        try {
          lock.lock();
          System.out.println(Thread.currentThread().getName()+"读数据");
          TimeUnit.SECONDS.sleep(3);
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          lock.unlock();
        }

      }).start();
    }
  }

2.写写互斥

public static void main(String[] args) {
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    for (int i = 0; i < 5; i++) {
      new Thread(()->{
        Lock lock = readWriteLock.writeLock();
        try {
          lock.lock();
          System.out.println(Thread.currentThread().getName()+"写数据");
          TimeUnit.SECONDS.sleep(3);
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          lock.unlock();
        }

      }).start();
    }
  }

3.读写互斥,写读互斥就先不演示了。

public static void main(String[] args) {
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    new Thread(()->{
      Lock lock = readWriteLock.readLock();
      try {
        lock.lock();
        System.out.println(Thread.currentThread().getName()+"0秒开始读数据,需要读5秒");
        TimeUnit.SECONDS.sleep(5);

      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        lock.unlock();
        System.out.println(Thread.currentThread().getName()+"读完毕,释放读锁");
      }
    }).start();

    new Thread(()->{
      Lock lock = readWriteLock.writeLock();
      try {
        TimeUnit.SECONDS.sleep(3);
        lock.lock();
        System.out.println(Thread.currentThread().getName()+"3秒后开始开始写数据,瞬间写完");
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        lock.unlock();
        System.out.println(Thread.currentThread().getName()+"写完毕,释放读锁");
      }
    }).start();
  }

 

7.ReadWriteLock的使用以及源码解读

原文:https://www.cnblogs.com/johnzhao/p/15025985.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!