JAVA学习——基于AQS的ReentrantLock公平锁和非公平锁的实现

2024-05-01 22:08

本文主要是介绍JAVA学习——基于AQS的ReentrantLock公平锁和非公平锁的实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

之前笔者解析了AQS的源码,在JUC中有很多锁是基于AQS实现的,今天想写个简单的ReentrantLock实现,代码也基本是在看了ReentrantLock源码后写出来的,做个笔记。

总结一下AQS的原理,就是使用一个int类型来表示可申请的锁资源,提供了一系列的原子操作,以及用于放置申请锁的线程的等待队列。实际上定义了一整套完整的多线程访问共享资源的同步框架,具体的解析可以看我的另一篇文章

ReentrantLock非公平锁的实现

首先来看ReentrantLock的非公平锁实现,它的类定义:

public class UnfairReentrantLockImpl extends AbstractQueuedSynchronizer implements Lock, Serializable

非公平锁实现了Lock接口,因此需要实现以下的方法:
在这里插入图片描述
基本上只要了解接口的语义,基于AQS提供的接口,可以快速实现Lock的接口功能,代码如下,可以看到AQS提供的是线程同步部分的实现:

	public void lock() {//cas的方式修改state值,如果成功,即获得锁if (compareAndSetState(0, 1)) {setExclusiveOwnerThread(Thread.currentThread());} else {//否则加入等待队列,自旋方式申请锁acquire(1);}}@Overridepublic void unlock() {//释放锁release(1);}@Overridepublic boolean tryLock(long time, TimeUnit unit) throws InterruptedException 			{//阻塞方式申请锁,指定时间后无论是否申请成功都返回return tryAcquireNanos(1, unit.toNanos(time));}@Overridepublic boolean tryLock() {//非阻塞方式申请锁return nofairTryAcquire(1);}@Overridepublic void lockInterruptibly() throws InterruptedException {//可中断式的申请锁acquireInterruptibly(1);}@Overridepublic Condition newCondition() {return new ConditionObject();}//尝试获取锁private final boolean nofairTryAcquire(int acquires) {final Thread current = Thread.currentThread();int c = getState();if (c == 0) {if (compareAndSetState(0, acquires)) {setExclusiveOwnerThread(current);return true;}} else if (current == getExclusiveOwnerThread()) {//如果当前线程已经持有锁,只修改一下state的值即返回,//体现了可重入锁的特点int nextC = c + acquires;if (nextC < 0) {throw new Error("Maximum lock lcount exceeded");}setState(nextC);return true;}return false;}

ReentrantLock锁继承AQS,必须要实现AQS的两个方法:tryAcquire和tryRelease,这两个方法在AQS只提供了一个抛出异常的实现。tryAcquire的语义是非阻塞式的申请锁,而tryRelease的语义是释放锁,并恢复state的值。在AQS内部,会使用这两个方法构造整个同步器的实现。

    //AbstractQueuedSynchronizer定义的方法,该方法在AbstractQueuedSynchronizer中只有一个抛出异常的默认实现@Overrideprotected boolean tryAcquire(int arg) {final Thread current = Thread.currentThread();int c = getState();if (c == 0) {if (compareAndSetState(0, arg)) {setExclusiveOwnerThread(current);return true;}} else if (current == getExclusiveOwnerThread()) {int nextC = c + arg;if (nextC < 0) {throw new Error("Maximum lock lcount exceeded");}setState(nextC);return true;}return false;}//AbstractQueuedSynchronizer定义的方法,该方法在AbstractQueuedSynchronizer中只有一个抛出异常的默认实现@Overrideprotected boolean tryRelease(int arg) {int c = getState() - arg;if (Thread.currentThread() != getExclusiveOwnerThread())throw new IllegalMonitorStateException();boolean free = false;if (c == 0) {free = true;setExclusiveOwnerThread(null);}setState(c);return free;}

ReentrantLock公平锁的实现
ReentrantLock公平锁强调根据线程等待时间长短来分配锁,等待时间最长的获取锁,在实现上,会让等待队列头部的线程获得锁。
公平锁的代码实现与非公平锁基本一致,主要区别在以下两个方法上,公平锁的lock方法会将申请锁的线程直接加入等待队列,根据等待时间排序来决定获取锁的线程。公平锁的tryAcquire方法在判断一个线程能否获得锁时,会比非公平锁多加入一个请求线程是否为头线程的判断,只有头线程能获得线程。读者可以与非公平锁的这两个方法实现进行对比,即可清楚比较出两者的区别

	@Overridepublic void lock() {//与非公平锁的区别:直接将当前申请锁请求加入队列acquire(1);}@Overrideprotected boolean tryAcquire(int arg) {final Thread current = Thread.currentThread();int c = getState();if (c == 0) {//只有在当前线程为头结点时,才能去获得锁if (!hasQueuedPredecessors() && compareAndSetState(0, arg)) {setExclusiveOwnerThread(current);return true;}} else if (current == getExclusiveOwnerThread()) {int nextC = c + arg;if (nextC < 0) {throw new Error("Maximum lock count exceeded");}setState(nextC);return true;}return false;}

ReentrantLock的测试

最后,给出一个简单的测试类,这个测试类创建了10个银行账户,初始金额都为1000元,然后有30个管理线程,会随机挑选两个账户,转账一个10以内的随机金额,每个线程独立转账10次。完成所有的转账操作后,计算所有账户总金额,如果总金额与原来一致,证明整个转账过程没有同步错误。


public class LockTest {private static Account[] accounts = new Account[10];private static AccountManager[] threads = new AccountManager[30];public static void main(String[] args) throws Exception {for (int i = 0; i < 10; i++) {accounts[i] = new Account(1000);}double sum = 0;for (int i = 0; i < 10; i++) {sum += accounts[i].getMoney();}System.out.println("src sum:" + sum);for (int i = 0; i < 30; i++) {threads[i] = new AccountManager();threads[i].start();}for (int i = 0; i < 30; i++) {threads[i].join();}sum = 0;for (int i = 0; i < 10; i++) {sum += accounts[i].getMoney();}System.out.println("after operation sum:" + sum);for (int i = 0; i < accounts.length; i++) {System.out.println("acount-" + i + " res money: " + accounts[i].getMoney());}}private static class AccountManager extends Thread {@Overridepublic void run() {int index = 10;int fromAccount = 0, toAccount = 0;while (index > 0) {fromAccount = (int) (Math.random() * 10);toAccount = (int) (Math.random() * 10);if (toAccount == fromAccount) {toAccount = (toAccount + 1) % 10;}try {AccountMgr.transfer(accounts[fromAccount], accounts[toAccount], Math.random() * 10);} catch (Exception e) {e.printStackTrace();}index--;System.out.println(Thread.currentThread() + " complete " + (10 - index) + " transformation from " + fromAccount + " to " + toAccount);}}}
}public class Account {private Lock lock = new FairReentrantLockImpl();private volatile double money;public Account(final double money) {this.money = money;}public void add(double money) {lock.lock();try {this.money += money;} finally {lock.unlock();}}public void reduce(double money) {lock.lock();try {this.money -= money;} finally {lock.unlock();}}public double getMoney() {return money;}void lock() {lock.lock();}void unLock() {lock.unlock();}boolean tryLock() {return lock.tryLock();}
}
public class AccountMgr {public static boolean tryTransfer(Account from, Account to, Double money) throws NoEnoughMoneyException {if (from.tryLock()) {try {if (to.tryLock()) {try {if (from.getMoney() >= money) {from.reduce(money);to.add(money);} else {System.out.println("operation failed ");
//                            throw new NoEnoughMoneyException();}return true;} finally {to.unLock();}}} finally {from.unLock();}}return false;}public static void transfer(Account from, Account to, Double money) throws NoEnoughMoneyException {boolean success = false;do {success = tryTransfer(from, to, money);if (!success)Thread.yield();} while (!success);}public static class NoEnoughMoneyException extends Exception {}
}

这篇关于JAVA学习——基于AQS的ReentrantLock公平锁和非公平锁的实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/952781

相关文章

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

java中反射Reflection的4个作用详解

《java中反射Reflection的4个作用详解》反射Reflection是Java等编程语言中的一个重要特性,它允许程序在运行时进行自我检查和对内部成员(如字段、方法、类等)的操作,本文将详细介绍... 目录作用1、在运行时判断任意一个对象所属的类作用2、在运行时构造任意一个类的对象作用3、在运行时判断

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

golang版本升级如何实现

《golang版本升级如何实现》:本文主要介绍golang版本升级如何实现问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录golanwww.chinasem.cng版本升级linux上golang版本升级删除golang旧版本安装golang最新版本总结gola

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

Mysql实现范围分区表(新增、删除、重组、查看)

《Mysql实现范围分区表(新增、删除、重组、查看)》MySQL分区表的四种类型(范围、哈希、列表、键值),主要介绍了范围分区的创建、查询、添加、删除及重组织操作,具有一定的参考价值,感兴趣的可以了解... 目录一、mysql分区表分类二、范围分区(Range Partitioning1、新建分区表:2、分