C/C++教程

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

本文主要是介绍7.ReadWriteLock的使用以及源码解读,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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的使用以及源码解读的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!