首页javalockJava Thread - 如何使用ReentrantReadWriteLock

Java Thread - 如何使用ReentrantReadWriteLock

我们想知道如何使用ReentrantReadWriteLock。
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Main {
  static final Main instance = new Main();
  int counter = 0;
  ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(true);

  public void read() {
    while (true) {
      rwl.readLock().lock();
      try {
        System.out.println("Counter is " + counter);
      } finally {
        rwl.readLock().unlock();
      }
      try {
        Thread.currentThread().sleep(1000);
      } catch (Exception ie) {
      }
    }
  }

  public void write() {
    while (true) {
      rwl.writeLock().lock();
      try {
        counter++;
        System.out.println("Incrementing counter.  Counter is " + counter);
      } finally {
        rwl.writeLock().unlock();
      }
      try {
        Thread.currentThread().sleep(3000);
      } catch (Exception ie) {
      }
    }
  }
  public static void main(String[] args) {
      instance.write();
      instance.read();
  }
}