package com.itheima.d3_thread_safe; public class Account { private String
cardId; private double money; //账户的余额 public Account() { } public
Account(String cardId, double money) { this.cardId = cardId; this.money =
money; } /** * 小明 小红 * @return */ public void drawMoney(double money) {
//0.先获取是谁来取钱,线程的名字就是人名 String name = Thread.currentThread().getName();
//1.判断账户是否够钱 if(this.money >= money){ //2.取钱 System.out.println(name +
"来取钱成功,吐出:" + money); //3.更新余额 this.money -= money; System.out.println(name +
"取钱后剩余:" + this.money); }else{ //4.余额不足 System.out.println(name + "来取钱,余额不足!");
} } public String getCardId() { return cardId; } public void setCardId(String
cardId) { this.cardId = cardId; } public double getMoney() { return money; }
public void setMoney(double money) { this.money = money; } } package
com.itheima.d3_thread_safe; /** * 取钱的线程类 */ public class DrawThread extends
Thread{ //接受处理的账户对象。 private Account acc; public DrawThread(Account acc, String
name){ super(name); this.acc = acc; } @Override public void run() { //小明 小红
:取钱的 acc.drawMoney(100000); } } package com.itheima.d3_thread_safe; public
class ThreadDemo { public static void main(String[] args) {
//1.定义线程类,创建一个共享的账户对象 Account acc = new Account("ICBC-111",100000);
//2.创建2个线程对象,代表小明和小红同时进来了。 new DrawThread(acc,"小明").start(); new
DrawThread(acc,"小红").start(); } }

 

技术
友情链接
码工具
Toolsou
API参考文档
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信