前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JDK源码分析-Lock&Condition

JDK源码分析-Lock&Condition

作者头像
WriteOnRead
发布2019-08-16 17:11:04
3030
发布2019-08-16 17:11:04
举报
文章被收录于专栏:WriteOnReadWriteOnReadWriteOnRead

概述

涉及多线程问题,往往绕不开「锁」。在 JDK 1.5 之前,Java 通过 synchronized 关键字来实现锁的功能,该方式是语法层面的,由 JVM 实现。JDK 1.5 增加了锁在 API 层面的实现,也就是 java.util.concurrent.locks.Lock 接口及其相关的实现类,它不仅具备 synchronized 的功能,而且还增加了更加丰富的功能。通常与其配合使用的还有 Condition 接口。

本文先简要分析下接口定义,后文再分析相关实现类的原理。

接口分析

Lock 接口的定义如下:

public interface Lock {
    // 阻塞式获取锁,该方法与synchronized功能类似
    void lock();
   
    // 获取锁,可响应中断
    void lockInterruptibly() throws InterruptedException;
    
    // 尝试获取锁,若成功返回true;否则返回false
    boolean tryLock();
    
    // 尝试获取锁(在给定的时间内),若成功返回true;否则返回false
    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
    
    // 释放锁
    void unlock();
    
    // 创建一个与该锁绑定的Condition
    Condition newCondition();
}

Condition 接口定义如下:

public interface Condition {
    // 使当前线程等待,直到被signal唤醒或被中断
    void await() throws InterruptedException;

    // 使当前线程等待,直到被signal唤醒(不响应中断)
    void awaitUninterruptibly();
    
    // 使当前线程等待,直到被signal唤醒、或被中断、或到达等待时间
    long awaitNanos(long nanosTimeout) throws InterruptedException;
    
    // 使当前线程等待,直到被signal唤醒、或被中断、或到达等待时间(与上面方法类似)
    boolean await(long time, TimeUnit unit) throws InterruptedException;
    
    // // 使当前线程等待,直到被signal唤醒、或被中断、或到达给定的截止时间
    boolean awaitUntil(Date deadline) throws InterruptedException;
    
    // 唤醒一个等待的线程
    void signal();
    
    // 唤醒所有等待的线程
    void signalAll();
}

Condition 的方法虽然不少,但其实就两类:

1. await* 方法,让当前线程处于等待状态;

2. signal* 方法,唤醒处于等待的线程。

此外,还有一个 ReadWriteLock 接口:

public interface ReadWriteLock {
    // 读锁
    Lock readLock();

    // 写锁
    Lock writeLock();
}

定义了读锁和写锁,其中读锁是共享的,写锁是互斥的。

代码示例

以典型的“生产者-消费者”模型为例,下面分别使用 synchronized 和 Lock 方式来实现并比较其用法。

使用 synchronized 和 wait/notify 实现,示例代码:

public class ProdConsumerTest {
  private static final Object monitor = new Object();
  private Random random = new Random();
  private static final int SIZE = 10;
  private Queue<Integer> queue = new LinkedList<>();

  private void produce() throws InterruptedException {
    for (; ; ) {
      synchronized (monitor) {
        if (queue.size() >= SIZE) {
          monitor.wait();
        }
        int nextInt = random.nextInt(1000);
        queue.offer(nextInt);

        sleep(400);
        System.out.println("size=" + queue.size() + ", 生产-->" + nextInt);
        monitor.notify();
      }
    }
  }

  private void consume() throws InterruptedException {
    for (; ; ) {
      synchronized (monitor) {
        if (queue.size() <= 0) {
          monitor.wait();
        }
        Integer poll = queue.poll();

        sleep(300);
        System.out.println("size=" + queue.size() + ", 消费成功-->" + poll);
        monitor.notify();
      }
    }
  }

  private void sleep(int timeout) {
    try {
      TimeUnit.MILLISECONDS.sleep(timeout);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    ProdConsumerTest test = new ProdConsumerTest();
    Thread t1 = new Thread(() -> {
      try {
        test.produce();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    });

    Thread t2 = new Thread(() -> {
      try {
        test.consume();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    });

    t1.start();
    t2.start();
  }
}

使用 Lock/Condition 实现,示例代码:

public class ProdConsumerTest {
  private static final int SIZE = 10;
  private Random random = new Random();
  private Queue<Integer> queue = new LinkedList<>();

  // ReentrantLock 是 JDK 提供的 Lock 接口实现类,后文分析其原理
  private Lock lock = new ReentrantLock();
  private Condition notFull = lock.newCondition();
  private Condition notEmpty = lock.newCondition();

  private void produce() throws InterruptedException {
    for (; ; ) {
      lock.lock();
      try {
        if (queue.size() >= SIZE) {
          notFull.await();
        }
        int nextInt = random.nextInt(1000);
        queue.offer(nextInt);

        sleep(400);
        System.out.println("size=" + queue.size() + ", 生产-->" + nextInt);
        notEmpty.signal();
      } finally {
        lock.unlock();
      }
    }
  }

  private void consume() throws InterruptedException {
    for (; ; ) {
      lock.lock();
      try {
        if (queue.size() <= 0) {
          notEmpty.await();
        }
        Integer poll = queue.poll();

        sleep(300);
        System.out.println("size=" + queue.size() + ", 消费成功-->" + poll);
        notFull.signal();
      } finally {
        lock.unlock();
      }
    }
  }

  private void sleep(int timeout) {
    try {
      TimeUnit.MILLISECONDS.sleep(timeout);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    ProdConsumerTest test = new ProdConsumerTest();
    Thread t1 = new Thread(() -> {
      try {
        test.produce();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    });

    Thread t2 = new Thread(() -> {
      try {
        test.consume();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    });

    t1.start();
    t2.start();
  }
}

通过对比发现,Lock/Condition 可以实现和 synchronized 一样的功能,而 Condition 的 await/signal 则相当于 Object 的 wait/notify。

本文简要分析了 Lock 和 Condition 接口,后文再分析它们的实现原理。

Stay hungry, stay foolish.

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-05-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 WriteOnRead 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档