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();
  }

 

上一篇:线程优先级


下一篇:Java多线程资源共享