Multithreaded read-write lock

 

/**
 * Read-write lock: divided into read lock and write lock, multiple read locks are not mutually exclusive, read lock and write lock are mutually exclusive, which is controlled by JVM itself,
 * We only need to lock the corresponding lock . If your code is read-only data, many people can read at the same time, but cannot write at the same time,
 * then lock the read lock; if your code modifies the data, only one person is writing, and cannot be read at the same time, then write Lock.
 * In short, the read lock is applied when reading, and the write lock is applied when writing!
 *
 * ReentrantReadWriteLock--As the name suggests, it is a reentrant read-write lock,
 * allows multiple read threads to obtain ReadLock, but only one writer thread is allowed to obtain WriteLock
 *
 * Read-write lock is an advanced thread lock mechanism. Multiple threads are allowed to read a particular resource at the same time,
 * but only one thread can write to it at a time.
 */
public class ReadWriteLockTest {
 private User user = new User();
 private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

 public static void main(String[] args) {
  ReadWriteLockTest o = new ReadWriteLockTest();
  o.user.setName("w");
  o.user.setDesc("w");
  
  for(int i=0;i<50;i++) {
   o.new Read().start();
   o.new Write().start();
  }
 }

 class User{
  private String name;
  private String desc;
  
  public String getName() {
   return name;
  }
  public void setName(String name) {
   this.name = name;
  }
  public String getDesc() {
   return desc;
  }
  public void setDesc(String desc) {
   this.desc = desc;
  }
 }
 
 class Read extends Thread{
  public void run() {
   lock.readLock().lock(); //获取值用读锁
    System.out.println(user.getName() + ","+user.getDesc());
   lock.readLock().unlock();
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
 
 class Write extends Thread{
  public void run() {
   lock.writeLock().lock(); //设值用写锁
    String name = new Random().nextInt(100) + "";
    user.setName(name);
    
    try {
     Thread.sleep(10);
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    user.setDesc(name);
   lock.writeLock().unlock();
  }
 }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326032049&siteId=291194637