当前位置: 首页 > news >正文

ReentrantLock实现公平锁,可中断,条件变量,可重入案例

1.ReentrantLock实现公平锁

/*** ReentrantLock实现公平锁* 创建了三个线程,依次打印线程*/
public class FairLockExample {private static ReentrantLock fairLock = new ReentrantLock(true); // 创建公平锁public static void main(String[] args) {Runnable fairTask = new FairTask();// 创建多个线程来竞争公平锁Thread thread1 = new Thread(fairTask, "Thread-1");Thread thread2 = new Thread(fairTask, "Thread-2");Thread thread3 = new Thread(fairTask, "Thread-3");thread1.start();thread2.start();thread3.start();}static class FairTask implements Runnable {@Overridepublic void run() {while (true) {try {fairLock.lock();System.out.println(Thread.currentThread().getName() + " 获取到锁");Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} finally {fairLock.unlock();System.out.println(Thread.currentThread().getName() + " 释放锁");}}}}
}

输出结果

Thread-1 获取到锁
Thread-1 释放锁
Thread-2 获取到锁
Thread-2 释放锁
Thread-3 获取到锁
Thread-3 释放锁
Thread-1 获取到锁
Thread-1 释放锁
Thread-2 获取到锁
Thread-2 释放锁
Thread-3 获取到锁
Thread-3 释放锁
Thread-1 获取到锁
Thread-1 释放锁
Thread-2 获取到锁
Thread-2 释放锁
Thread-3 获取到锁

2.ReentrantLock实现可中断锁

/*** 演示ReentrantLock调用lockInterruptibly方法可以被中断* https://blog.csdn.net/ZSA222/article/details/123433746?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522170022637516800182740333%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=170022637516800182740333&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-1-123433746-null-null.142^v96^pc_search_result_base5&utm_term=ReentrantLock&spm=1018.2226.3001.4187*/
public class ReentrantLockInterrupt {private static ReentrantLock lock = new ReentrantLock();public static void main(String[] args) throws InterruptedException {Thread thread = new Thread(() -> {try {// 如果没有竞争那么此方法就会获取 lock 对象锁// 如果有竞争就进入阻塞队列,可以被其它线程用 interruput 方法打断System.out.println(Thread.currentThread().getName() +  LocalDateTime.now() + "尝试获得锁");Thread.sleep(15000);lock.lockInterruptibly();} catch (InterruptedException e) {e.printStackTrace();System.out.println(Thread.currentThread().getName() + LocalDateTime.now() + "t1线程没有获得锁,被打断...return");return;}try {System.out.println(Thread.currentThread().getName() + LocalDateTime.now() + "t1线程获得了锁");} finally {lock.unlock();}}, "t1");// t1启动前 主线程先获得了锁lock.lock();thread.start(); // thread线程会进入阻塞队列Thread.sleep(5000);System.out.println(Thread.currentThread().getName() + LocalDateTime.now() + "interrupt...打断t1");Thread.sleep(2000);thread.interrupt();}
}

输出结果

t111:27:23尝试获得锁
main11:27:28interrupt...打断t1
java.lang.InterruptedException: sleep interruptedat java.lang.Thread.sleep(Native Method)at concurrentpro.lock.ReentrantLockInterrupt.lambda$main$0(ReentrantLockInterrupt.java:20)at java.lang.Thread.run(Thread.java:750)
t111:27:30t1线程没有获得锁,被打断...return
/*** 演示ReentrantLock调用普通lock方法,不能被中断* https://blog.csdn.net/ZSA222/article/details/123433746?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522170022637516800182740333%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=170022637516800182740333&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-1-123433746-null-null.142^v96^pc_search_result_base5&utm_term=ReentrantLock&spm=1018.2226.3001.4187*/
public class ReentrantLock {private static java.util.concurrent.locks.ReentrantLock lock = new java.util.concurrent.locks.ReentrantLock();public static void main(String[] args) throws InterruptedException {Thread thread = new Thread(() -> {System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("hh:mm:ss")) + Thread.currentThread().getName() + "尝试获得锁");lock.lock();try {System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("hh:mm:ss")) + Thread.currentThread().getName() + "t1线程获得了锁");} finally {lock.unlock();}}, "t1");// t1启动前 主线程先获得了锁lock.lock();thread.start();Thread.sleep(1000);System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("hh:mm:ss")) + Thread.currentThread().getName() + "interrupt...打断t1");thread.interrupt();}
}

输出结果 

11:24:39t1尝试获得锁
11:24:40maininterrupt...打断t1

3.ReentrantLock实现条件变量


/*** ReentrantLock 之 condtion的用法* 配合 condition.await 和 condition.signal* 来源:bilibli 黑马程序员之并发编程*/
public class ConditionVariable {private static boolean hasCigarette = false;private static boolean hasTakeout = false;private static final ReentrantLock lock = new ReentrantLock();// 等待烟的休息室(条件变量)static Condition waitCigaretteSet = lock.newCondition();// 等外卖的休息室(条件变量)static Condition waitTakeoutSet = lock.newCondition();public static void main(String[] args) throws InterruptedException {new Thread(() -> {lock.lock();try {System.out.println(LocalTime.now() +  Thread.currentThread().getName() + "有烟没?[{}]" + hasCigarette);while (!hasCigarette) {System.out.println(LocalTime.now() +   Thread.currentThread().getName()  +"没烟,先歇会!");try {// 此时小南进入到 等烟的休息室waitCigaretteSet.await();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(LocalTime.now() +  Thread.currentThread().getName()  + "烟来咯, 可以开始干活了");} finally {lock.unlock();}}, "小南").start();new Thread(() -> {lock.lock();try {System.out.println(LocalTime.now() +  Thread.currentThread().getName()  +"外卖送到没?[{}]" + hasTakeout);while (!hasTakeout) {System.out.println(LocalTime.now() +  Thread.currentThread().getName()  + "没外卖,先歇会!");try {// 此时小女进入到 等外卖的休息室waitTakeoutSet.await();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(LocalTime.now() +   Thread.currentThread().getName()  +"外卖来咯, 可以开始干活了");} finally {lock.unlock();}}, "小女").start();Thread.sleep(1000);new Thread(() -> {lock.lock();try {System.out.println(LocalTime.now() +  Thread.currentThread().getName()  + "送外卖的来咯~");hasTakeout = true;// 唤醒等外卖的小女线程waitTakeoutSet.signal();} finally {lock.unlock();}}, "送外卖的").start();Thread.sleep(1000);new Thread(() -> {lock.lock();try {System.out.println(LocalTime.now() +  Thread.currentThread().getName()  +"送烟的来咯~");hasCigarette = true;// 唤醒等烟的小南线程waitCigaretteSet.signal();} finally {lock.unlock();}}, "送烟的").start();}
}

输出结果

11:29:38.644小南有烟没?[{}]false
11:29:38.645小南没烟,先歇会!
11:29:38.645小女外卖送到没?[{}]false
11:29:38.645小女没外卖,先歇会!
11:29:39.620送外卖的送外卖的来咯~
11:29:39.620小女外卖来咯, 可以开始干活了
11:29:40.621送烟的送烟的来咯~
11:29:40.621小南烟来咯, 可以开始干活了

4.ReentrantLock实现可重入

public class ReentrantLockExample {private ReentrantLock lock = new ReentrantLock();public void performTask() {lock.lock();try {System.out.println("Task started");// 可以多次获取锁lock.lock();try {System.out.println("Task is performing");} finally {lock.unlock();System.out.println("Inner lock released");}System.out.println("Task completed");} finally {lock.unlock();System.out.println("Outer lock released");}}public static void main(String[] args) {ReentrantLockExample example = new ReentrantLockExample();example.performTask();}
}

输出结果

Task started
Task is performing
Inner lock released
Task completed
Outer lock released

相关文章:

  • 跟我学c++中级篇——模板的调试
  • string类的总结
  • springboot jar包 无法读取静态资源文件
  • py 异步
  • 【2】SM2验签工具和RSA验签工具
  • EasyExcel导入从第几行开始
  • Linux的几个常用基本指令
  • 对象和数据结构
  • 【AI视野·今日Robot 机器人论文速览 第六十二期】Wed, 25 Oct 2023
  • debian 修改镜像源为阿里云【详细步骤】
  • Leetcode 【2342. 数位和相等数对的最大和】
  • 【Spring】AOP进阶-JoinPoint和ProceedingJoinPoint详解
  • 实力进阶,教你使用thinkphp6开发一款商城系统
  • 电力感知边缘计算网关产品设计方案-网关软件架构
  • 金融业务系统: Service Mesh用于安全微服务集成
  • Angular 2 DI - IoC DI - 1
  • Apache Spark Streaming 使用实例
  • Docker容器管理
  • Java深入 - 深入理解Java集合
  • Java新版本的开发已正式进入轨道,版本号18.3
  • JDK9: 集成 Jshell 和 Maven 项目.
  • PAT A1050
  • python 装饰器(一)
  • vue从创建到完整的饿了么(11)组件的使用(svg图标及watch的简单使用)
  • yii2中session跨域名的问题
  • 安装python包到指定虚拟环境
  • 从零搭建Koa2 Server
  • 大整数乘法-表格法
  • 对话 CTO〡听神策数据 CTO 曹犟描绘数据分析行业的无限可能
  • 爬虫进阶 -- 神级程序员:让你的爬虫就像人类的用户行为!
  • 让你成为前端,后端或全栈开发程序员的进阶指南,一门学到老的技术
  • 数据库写操作弃用“SELECT ... FOR UPDATE”解决方案
  • 移动端唤起键盘时取消position:fixed定位
  • [Shell 脚本] 备份网站文件至OSS服务(纯shell脚本无sdk) ...
  • 【运维趟坑回忆录】vpc迁移 - 吃螃蟹之路
  • ​DB-Engines 11月数据库排名:PostgreSQL坐稳同期涨幅榜冠军宝座
  • ​LeetCode解法汇总2670. 找出不同元素数目差数组
  • ​马来语翻译中文去哪比较好?
  • #QT(一种朴素的计算器实现方法)
  • #我与Java虚拟机的故事#连载13:有这本书就够了
  • (4) openssl rsa/pkey(查看私钥、从私钥中提取公钥、查看公钥)
  • (ros//EnvironmentVariables)ros环境变量
  • (搬运以学习)flask 上下文的实现
  • (附源码)springboot宠物管理系统 毕业设计 121654
  • (论文阅读32/100)Flowing convnets for human pose estimation in videos
  • (南京观海微电子)——COF介绍
  • (牛客腾讯思维编程题)编码编码分组打印下标(java 版本+ C版本)
  • (七)微服务分布式云架构spring cloud - common-service 项目构建过程
  • (算法)N皇后问题
  • (原創) 是否该学PetShop将Model和BLL分开? (.NET) (N-Tier) (PetShop) (OO)
  • .babyk勒索病毒解析:恶意更新如何威胁您的数据安全
  • .FileZilla的使用和主动模式被动模式介绍
  • .form文件_一篇文章学会文件上传
  • .NetCore项目nginx发布
  • .net快速开发框架源码分享