ReentrantReadWriteLock:ReadLock和WriteLock有什么区别? [英] ReentrantReadWriteLock: what's the difference between ReadLock and WriteLock?

查看:151
本文介绍了ReentrantReadWriteLock:ReadLock和WriteLock有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所知道的是:

  • ReadLock and WriteLock affect each other somehow
  • WriteLock is just like synchronized
  • ReadLock seems cannot work alone

推荐答案

readLock.lock();

  • 这意味着,如果有任何其他线程正在编写(即持有一个 写锁),然后在此处停止,直到没有其他线程在写.
  • 授予该锁后,将不允许其他任何线程写入 (即使用写锁),直到释放该锁为止.
  • readLock.lock();

    • This means that if any other thread is writing (i.e. holds a write lock) then stop here until no other thread is writing.
    • Once the lock is granted no other thread will be allowed to write (i.e. take a write lock) until the lock is released.
      • 这意味着,如果有任何其他线程正在阅读写作,请停止 在这里,直到没有其他线程正在读取或写入.
      • 授予锁定后,将不允许其他任何线程读取 (即获取读或写锁),直到释放该锁为止.
      • This means that if any other thread is reading or writing, stop here and wait until no other thread is reading or writing.
      • Once the lock is granted, no other thread will be allowed to read or write (i.e. take a read or write lock) until the lock is released.

      结合使用这些,您一次只能安排一个线程进行写访问,但是,除了一个线程正在写时,您可以同时阅读任意数量的阅读器.

      Combining these you can arrange for only one thread at a time to have write access, but as many readers as you like can read at the same time except when a thread is writing.

      另辟way径.每次您要从结构中读取时,请锁定读取.每次您要写入时,请进行写入锁定.这样一来,只要发生写操作,就不会有人在阅读(您可以想象您具有独占访问权),但是只要没有人在写,就会有许多读者同时阅读.

      Put another way. Every time you want to read from the structure, take a read lock. Every time you want to write, take a write lock. This way whenever a write happens no-one is reading (you can imagine you have exclusive access), but there can be many readers reading at the same time so long as no-one is writing.

      这篇关于ReentrantReadWriteLock:ReadLock和WriteLock有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆