需求:
一个人通过一个账户在柜台取钱和在ATM机取钱
Bank类
[AppleScript] 纯文本查看 复制代码 public class Bank {
//创建一个银行账户,余额有1000,元
static int monry = 1000;
//柜员机取钱
public void count(int money) {
Bank.monry -= money;
System.out.println("柜台取钱" + money + "元,还剩" + Bank.monry + "元.");
}
//ATM取钱
public void Atm(int money) {
Bank.monry -= money;
System.out.println("ATM机取钱" + money + "元,还剩" + Bank.monry + "元.");
}
//定义一个方法用来取钱
public void outMoney(int money, String mode) {
//同步
synchronized (this) {
//判断余额是否充足
if (money > Bank.monry) {
try {
throw new Exception("取款金额" + money + "元,还剩" + Bank.monry + "元,取款失败");
} catch (Exception e) {
e.printStackTrace();
}
}
//判断是用哪种方式取钱
if (Objects.equals(mode, "ATM")) {
Atm(money);
} else {
count(money);
}
}
}
}
Person类
[Java] 纯文本查看 复制代码 public class Person extends Thread {
private Bank bank;
private String mode;
private int money;
//全参构造方法
public Person(Bank bank, String mode, int money) {
this.bank = bank;
this.mode = mode;
this.money = money;
}
//重写run方法
@Override
public void run() {
//死循环,如果余额大于取款金额
while (bank.monry >= money) {
bank.outMoney(money, mode);
//系统睡眠1秒
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试类
[AppleScript] 纯文本查看 复制代码 public class Demo01MyBank {
public static void main(String[] args) {
Bank b = new Bank();
//创建两个对象,认为是一个人在不同的地方对同一张卡取钱
Person p1 = new Person(b, "ATM", 100);
Person p2 = new Person(b, "柜台", 200);
//调用方法.
p1.start();
p2.start();
}
}
一个简单的小实例,
喜欢的童鞋可以收藏.
|
|