2021-04-18 11:26  阅读(64)
文章分类:Java 基础教程 文章标签:JavaJava 教程
©  原文作者:w3cschool 原文地址:https://www.w3cschool.cn/java/java-thread-multiple.html

Java线程教程 - Java显式锁

显式锁定机制可以用于协调对多线程环境中的共享资源的访问。

在java.util.concurrent.locks包中声明的Lock接口定义了显式锁定操作。

ReentrantLock类在同一个包中,是Lock接口的具体实现。

Lock接口声明如下:

    public interface Lock {
      void lock();
    
      Condition newCondition();
    
      void lockInterruptibly() throws InterruptedException;
    
      boolean tryLock();
    
      boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
    
      void unlock();
    }
    

lock()方法获取一个锁的行为与使用synchronized关键字相同。

我们必须在完成锁定后通过调用Lock接口的unlock()方法释放锁定。

    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class Main {
      // Instantiate the lock object
      private Lock myLock = new ReentrantLock();
    
      public void updateResource() {
    
        try {
          // Acquire the lock
          myLock.lock();
        } finally {
          // Release the lock
          myLock.unlock();
        }
      }
    }
    

例子

下面的代码模拟哲学家,假设ReentrantLock类的一个对象表示一个fork。

    import java.util.concurrent.locks.Lock;
    
    class Philosopher {
      private Lock leftFork;
      private Lock rightFork;
      private String name; // Philosopher"s name
    
      public Philosopher(Lock leftFork, Lock rightFork, String name) {
        this.leftFork = leftFork;
        this.rightFork = rightFork;
        this.name = name;
      }
    
      public void think() {
        System.out.println(name + "  is thinking...");
      }
    
      public void eat() {
        if (leftFork.tryLock()) {
          try {
            if (rightFork.tryLock()) {
              try {
                System.out.println(name + "  is eating...");
              } finally {
                rightFork.unlock();
              }
            }
          } finally {
            leftFork.unlock();
          }
        }
      }
    }
    

例2

ReentrantReadWriteLock类是ReadWriteLock接口的实现。只有一个线程可以保持ReentrantReadWriteLock的写锁,而多个线程可以保持其读锁。

下面的代码演示了ReentrantReadWriteLock的用法。

    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantReadWriteLock;
    
    public class Main {
      private int value;
      private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
      private Lock rLock = rwLock.readLock();
      private Lock wLock = rwLock.writeLock();
    
      public Main(int value) {
        this.value = value;
      }
    
      public int getValue() {
        rLock.lock();
        try {
          return this.value;
        } finally {
          rLock.unlock();
        }
      }
    
      public void setValue(int value) {
        wLock.lock();
        try {
          this.value = value;
        } finally {
          wLock.unlock();
        }
      }
    }
    
点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> Java 显式锁
上一篇
Java 原子变量
下一篇
Java 同步器