java 线程同步方法执行与唤醒实例
账号提钱、存钱实例方法
public class Account { private int balance; private int maxBalance; public Account(int balance) { this.balance=balance; } //同步方法 取钱 public synchronized void transferOut(int money) { //线程同步 //synchronized(this) { String theadName=Thread.currentThread().getName(); if(balance>money) { try { Thread.sleep(1); }catch(InterruptedException e ){ e.printStackTrace(); } balance=balance-money; System.out.println(theadName+"转走:"+money+",余额:"+balance); }else { System.out.println(Thread.currentThread().getName()+"余额不足"); } // } } //同步方法 线程等待 存钱 public synchronized void save(int money) { while(balance+money>maxBalance) { try { this.wait(); //线程等待 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } String theadName=Thread.currentThread().getName(); balance=balance+money; System.out.println( "save "+money+"元"+" balance:"+balance); this.notifyAll();//唤醒其它线程 } //同步方法 线程等待 存钱 public synchronized void withdraw(int money) { while(money>balance) { try { this.wait(); //线程等待 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } balance=balance-money; System.out.println( "take "+money+"元"+" balance:"+balance); this.notifyAll();//唤醒其它线程 } }
测试方法
public class Test { public static void main(String[] args) { Account account2=new Account(8000); Thread t1=new Thread(new TakeMoney(account2),"son1"); Thread t2=new Thread(new TakeMoney(account2),"son2"); t1.start(); t2.start(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律