JDK1.5新特性互斥锁
ReentrantLock介绍
- 使用ReentrantLock类也可以实现同步加锁
- ReentrantLock叫[互斥锁],使用lock()和unlock()方法进行同步
- 使用ReentrantLock类的newCondition()方法可以获取Condition对象
- 需要等待的时候使用Condition的await()方法, 唤醒的时候用signal()方法
- 不同的线程使用不同的Condition, 这样就能区分唤醒的时候找哪个线程了
使用ReentrantLock类使用要点
- 使用ReentrantLock类的newCondition()方法可以获取Condition对象
- 需要等待的时候使用Condition的await()方法, 唤醒的时候用signal()方法
- 不同的线程使用不同的Condition, 这样就能区分唤醒的时候找哪个线程了
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class ReentrantLockDemo { public static void main(String[] args) { MyTaskThree task = new MyTaskThree(); new Thread(() -> { while(true){ try { task.task1();//执行任务1 } catch (InterruptedException e) { e.printStackTrace(); } try{ Thread.sleep(10); }catch(InterruptedException e){ e.printStackTrace(); } } }).start(); new Thread(){ @Override public void run() { while(true){ try { task.task2();//执行任务2 } catch (InterruptedException e) { e.printStackTrace(); } try{ Thread.sleep(10); }catch(InterruptedException e){ e.printStackTrace(); } } } }.start(); new Thread(){ @Override public void run() { while(true){ try { task.task3();//执行任务3 } catch (InterruptedException e) { e.printStackTrace(); } try{ Thread.sleep(10); }catch(InterruptedException e){ e.printStackTrace(); } } } }.start(); } } /* /** * 互斥锁的使用步骤 * 1.创建互斥锁对象 * 2.创建3个Condition * 3.加锁、解锁 * 4.线程等待-Condition的await方法 * 5.线程唤醒-Condition的signal方法 * @author tuba * */ class MyTasks{ ReentrantLock r = new ReentrantLock(); Condition c1 = r.newCondition(); Condition c2 = r.newCondition(); Condition c3 = r.newCondition(); int flag = 1;//标识 1:可以执行任务1,2:可以执行任务2 public void task1() throws InterruptedException { r.lock(); if(flag != 1){ c1.wait();//当前线程等待 ,抛出中断异常 } System.out.println("1.银行信用卡自动还款任务..."); this.flag = 2; c2.signal();//唤醒指定线程2 r.unlock(); } public void task2() throws InterruptedException { r.lock(); if(flag != 2){ c2.wait();//当前线程等待 ,抛出中断异常 } System.out.println("2.银行储蓄卡自动结算利息任务..."); this.flag = 3; c3.signal();//唤醒指定线程3 r.unlock(); } public void task3() throws InterruptedException { r.lock(); if(flag != 3){ c3.wait();//当前线程等待 ,抛出中断异常 } System.out.println("3.银行短信提醒任务..."); this.flag = 1; c1.signal();//唤醒指定线程3 r.unlock(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?