从使用角度看 ReentrantLock 和 Condition
java 语言中谈到锁,少不了比较一番 synchronized 和 ReentrantLock 的原理,本文不作分析,只是简单介绍一下 ReentrantLock 的用法,从使用中推测其内部的一些原理。
代码示例:
- public static void main(String[] args) throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- final Condition con1 = lock.newCondition();
- final Condition con2 = lock.newCondition();
- // lock.lock();
- Thread t1 = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- lock.lock();
- con1.await();
- System.out.println("wake from cond1");
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- lock.unlock();
- }
- }
- });
- t1.start();
- Thread t2 = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- lock.lock();
- con2.await();
- System.out.println("wake from cond2");
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- lock.unlock();
- }
- }
- });
- t2.start();
- Thread t3 = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- lock.lock();
- con2.await();
- System.out.println("wake from cond2");
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- lock.unlock();
- }
- }
- });
- t3.start();
- Thread.sleep(100);
- try {
- lock.lock();
- System.out.println("lock.getQueueLength() = " + lock.getQueueLength());
- System.out.println("lock.getWaitQueueLength(con1) = " + lock.getWaitQueueLength(con1));
- System.out.println("lock.getWaitQueueLength(con2) = " + lock.getWaitQueueLength(con2));
- con1.signal();
- con2.signalAll();
- Thread.sleep(100);
- System.out.println("lock.getWaitQueueLength(con1) = " + lock.getWaitQueueLength(con1));
- System.out.println("lock.getWaitQueueLength(con2) = " + lock.getWaitQueueLength(con2));
- } finally {
- lock.unlock();
- }
- }
lock 和 await 会改变 state 的值。
以 ReentrantLock.getQueueLength 和 ReentrantLock.getWaitQueueLength 作为入口:前者作用是返回获取锁失败,处于等待状态的线程个数,后者是返回等待某一个 condition 的线程个数。
- // int java.util.concurrent.locks.ReentrantLock.getQueueLength()
- public final int getQueueLength() {
- return sync.getQueueLength();
- }
- // int java.util.concurrent.locks.AbstractQueuedSynchronizer.getQueueLength()
- public final int getQueueLength() {
- int n = 0;
- for (Node p = tail; p != null; p = p.prev) {
- if (p.thread != null)
- ++n;
- }
- return n;
- }
很简单,就是遍历阻塞线程的链表。
- // int java.util.concurrent.locks.ReentrantLock.getWaitQueueLength(Condition condition)
- public int getWaitQueueLength(Condition condition) {
- if (condition == null)
- throw new NullPointerException();
- if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
- throw new IllegalArgumentException("not owner");
- return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
- }
- // int java.util.concurrent.locks.AbstractQueuedSynchronizer.getWaitQueueLength(ConditionObject condition)
- public final int getWaitQueueLength(ConditionObject condition) {
- if (!owns(condition))
- throw new IllegalArgumentException("Not owner");
- return condition.getWaitQueueLength();
- }
- // int java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject.getWaitQueueLength()
- protected final int getWaitQueueLength() {
- if (!isHeldExclusively())
- throw new IllegalMonitorStateException();
- int n = 0;
- for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
- if (w.waitStatus == Node.CONDITION)
- ++n;
- }
- return n;
- }
同样,也是遍历链表,不同的是,这是 Condition 的链表。
现在,我们知道,ReentrantLock 中有 2 种不同的链表,其一是阻塞线程,其二是 Condition 等待链表,2 种链表都是使用 Node:
- // java.util.concurrent.locks.AbstractQueuedSynchronizer.Node
- static final class Node {
- static final Node EXCLUSIVE = null;
- // 线程阻塞节点的状态
- static final int CANCELLED = 1;
- static final int SIGNAL = -1;
- // condition 节点的状态
- static final int CONDITION = -2;
- static final int PROPAGATE = -3;
- volatile int waitStatus;
- volatile Node prev;
- volatile Node next;
- volatile Thread thread;
- }
节点的类型表明链表的类型。
看看 Condition 实现类的 api:
- public class ConditionObject implements Condition, java.io.Serializable {
- private static final long serialVersionUID = 1173984872572414699L;
- private transient Node firstWaiter;
- private transient Node lastWaiter;
- /**
- * Adds a new waiter to wait queue.
- * @return its new wait node
- */
- private Node addConditionWaiter() {
- Node t = lastWaiter;
- // If lastWaiter is cancelled, clean out.
- if (t != null && t.waitStatus != Node.CONDITION) {
- unlinkCancelledWaiters();
- t = lastWaiter;
- }
- Node node = new Node(Thread.currentThread(), Node.CONDITION);
- if (t == null)
- firstWaiter = node;
- else
- t.nextWaiter = node;
- lastWaiter = node;
- return node;
- }
- public final void await() throws InterruptedException {
- if (Thread.interrupted())
- throw new InterruptedException();
- Node node = addConditionWaiter();
- int savedState = fullyRelease(node);
- int interruptMode = 0;
- while (!isOnSyncQueue(node)) {
- LockSupport.park(this);
- if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
- break;
- }
- if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
- interruptMode = REINTERRUPT;
- if (node.nextWaiter != null) // clean up if cancelled
- unlinkCancelledWaiters();
- if (interruptMode != 0)
- reportInterruptAfterWait(interruptMode);
- }
- /**
- * Moves the longest-waiting thread, if one exists, from the
- * wait queue for this condition to the wait queue for the
- * owning lock.
- *
- * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
- * returns {@code false}
- */
- public final void signal() {
- if (!isHeldExclusively())
- throw new IllegalMonitorStateException();
- Node first = firstWaiter;
- if (first != null)
- doSignal(first);
- }
- }
在开头的示例中,创建了 2 个 Condition 对象,每个Condition 对象有一个自己的等待链表。
从使用角度看 ReentrantLock 和 Condition的更多相关文章
- Java多线程高并发学习笔记(二)——深入理解ReentrantLock与Condition
锁的概念 从jdk发行1.5版本之后,在原来synchronize的基础上,增加了重入锁ReentrantLock. 本文就不介绍synchronize了,有兴趣的同学可以去了解一下,本文重点介绍Re ...
- Java多线程之ReentrantLock与Condition
一.ReentrantLock 1.ReentrantLock简介 ReentrantLock是一个可重入的互斥锁,又被称为“独占锁”.ReentrantLock 类实现了 Lock ,它拥有与 sy ...
- Java多线程之wait、notify/notifyAll 详解,用wait 和notifyAll 以及synchronized实现阻塞队列,多线程拓展之ReentrantLock与Condition
前言:这几天看了很多关于多线程的知识,分享一波.(但是目前接触的项目还未用到过,最多用过线程池,想看线程池 请看我之前的博客) 关于基本的理论等 参考如下: https://www.cnblogs.c ...
- 使用 ReentrantLock 和 Condition 实现一个阻塞队列
前言 从之前的阻塞队列的源码分析中,我们知道,JDK 中的阻塞队列是使用 ReentrantLock 和 Condition 实现了,我们今天来个简易版的.代码如下: 代码 public class ...
- java 多线程 19: ReentrantLock 与 Condition
ReentrantLock ReentrantLock,一个可重入的互斥锁,它具有与使用synchronized方法和语句所访问的隐式监视器锁相同的一些基本行为和语义,但功能更强大. Reentran ...
- Java多线程(九)之ReentrantLock与Condition
一.ReentrantLock 类 1.1 什么是reentrantlock java.util.concurrent.lock 中的 Lock 框架是锁定的一个抽象,它允许把锁定的实现作为 ...
- ReentrantLock 和 Condition的使用
ReentrantLock ReentrantLock可以等同于synchronized使用. ReentrantLock 类实现了Lock ,它拥有与 synchronized 相同的并发性和内存 ...
- 【转】使用者角度看bionic pthread_mutex和linux futex实现
使用者角度看bionic pthread_mutex和linux futex实现 本文所大篇幅引用的参考文章主要描述针对glibc和pthread实现:而本文的考察代码主要是android的bioni ...
- Android IOS WebRTC 音视频开发总结(四八)-- 从商业和技术的角度看视频行业的机会
本文主要从不同角度介绍视频行业的机会,文章来自博客园RTC.Blacker,支持原创,转载必须说明出处,欢迎关注个人微信公众号blacker ----------------------------- ...
随机推荐
- 3.2 git命令大全
1. 常用命令 -- 查看 git remote:要查看当前配置有哪些远程仓库; git remote -v: -v 参数,你还可以看到每个别名的实际链接地址; git branch -a :查看远程 ...
- <script src="../build/browser.min.js"></script> 是用来里面babel工具把ES6的语法转成ES5
<!DOCTYPE html> <html> <head> <script src="../build/react.js">< ...
- MySQL的正则表达式的LIKE和REGEXP区别
LIKE匹配整个列.如果被匹配的文本在列值 中出现,LIKE将不会找到它,相应的行也不被返回(除非使用 通配符).而REGEXP在列值内进行匹配,如果被匹配的文本在 列值中出现,REGEXP将会找到它 ...
- C++的虚函数
1 多态产生的背景 希望同一个方法在派生类和基类中的行为是不同的,换句话来说,方法的行为取决于调用该方法的对象. 2 解决多态的两种方法 1)在派生类中重新定义基类的方法 2)使用虚方法 3 虚 ...
- Python全栈开发-Day5-常用模块学习
本节大纲: 模块介绍 time &datetime模块 random os sys shutil shelve xml处理 pyyaml处理 configparser hashlib re正则 ...
- 第 8 章 容器网络 - 053 - overlay 是如何隔离的?
overlay 是如何隔离的? 不同的 overlay 网络是相互隔离的. 创建第二个 overlay 网络 ov_net2 并运行容器 bbox3. docker network create -d ...
- (转)基于C#的socket编程的TCP异步实现
一.摘要 本篇博文阐述基于TCP通信协议的异步实现. 二.实验平台 Visual Studio 2010 三.异步通信实现原理及常用方法 3.1 建立连接 在同步模式中,在服务器上使用Accept方法 ...
- java8新特性(二)_lambda表达式
最近一直找java8相关新特性的文章,发现都太没有一个连贯性,毕竟大家写博客肯定都有自己的侧重点,这里找到一本书,专门介绍java8新特性的,感觉大家可以看看<写给大忙人看的JavaSE8> ...
- spring ----> 搭建spring+springmvc+mybatis出现的几个问题
环境: idea ce 2018.1+maven3.5.3+mysql8.0.11+jdk1.8 spring4.3.7+spring mvc4.3.7+mybatis3.4.1+tomcat7.0. ...
- LeetCode--012--整数转罗马数字(java)
罗马数字包含以下七种字符: I, V, X, L,C,D 和 M. 字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000 例如, 罗马数字 2 写做 II ,即为两个并 ...