JAVA全系列 教程
3762个小节阅读:7091.3k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
我们以银行取款经典案例来演示线程冲突现象。
银行取钱的基本流程基本上可以分为如下几个步骤。
(1)用户输入账户、密码,系统判断用户的账户、密码是否匹配。
(2)用户输入取款金额
(3)系统判断账户余额是否大于或等于取款金额
(4)如果余额大于或等于取款金额,则取钱成功;如果余额小于取款金额,则取钱失败。
xxxxxxxxxx
/**
* 账户类
*/
class Account{
//账号
private String accountNo;
//账户的余额
private double balance;
public Account() {
}
public Account(String accountNo, double balance) {
this.accountNo = accountNo;
this.balance = balance;
}
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
/**
* 取款线程
*/
class DrawThread implements Runnable{
//账户对象
private Account account;
//取款金额
private double drawMoney;
public DrawThread(Account account,double drawMoney){
this.account = account;
this.drawMoney = drawMoney;
}
/**
* 取款线程
*/
@Override
public void run() {
//判断当前账户余额是否大于或等于取款金额
if(this.account.getBalance() >= this.drawMoney){
System.out.println(Thread.currentThread().getName()+" 取钱成功!吐出钞票:"+this.drawMoney);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//更新账户余额
this.account.setBalance(this.account.getBalance()- this.drawMoney);
System.out.println("\t 余额为:"+this.account.getBalance());
}else{
System.out.println(Thread.currentThread().getName()+" 取钱失败,余额不足");
}
}
}
public class TestDrawMoneyThread {
public static void main(String[] args) {
Account account = new Account("1234",1000);
new Thread(new DrawThread(account,800),"老公").start();
new Thread(new DrawThread(account,800),"老婆").start();
}
}