查看本章节
查看作业目录
需求说明:
某用户共有两张银行卡,账户名称相同,但卡号和余额不同。模拟用户使用这两张银行卡进行消费的过程,并打印出消费明细
实现思路:
- 项目中创建账户类 Account,类中包括账户名称name、 ThreadLocal 类的引用变量amount,表示存款
- 创建消费类 DailyConsmption实现Runnable 接 口。声明 账户类型的引用 account, 使 用new Random() 实例化一个随机类对象 random,并定义一个初始化账户的构造方法
- 在run方法中调用 account 对象的setAmount存款方法,产生随机数表示存款金额,声明 double 类型的变量 consumptionAmount 和balance,分别表示每次的消费金额和银行卡余额
- 使用for循环模拟消费5次,判断余额是否大于等于 0,如果余额小于 0,则提示用户余额不足,不够此次消费,并结束循环。若余额大于等于 0,则输出此次的消费明细(包括账号名称、线程名称、消费金额和银行卡余额)
- 创建测试类,创建两个线程进行测试
实现代码:
账户类 Account
-
public
class Account {
-
//账号名称
-
private String name;
-
//定义一个ThreadLocal类型的变量,该变量将是线程的局部变量,用来保存不同银行卡的存款
-
private ThreadLocal<Double> amount =
new ThreadLocal<>();
-
//构造方法
-
public Account() {
-
super();
-
}
-
public Account(String name) {
-
super();
-
this.name = name;
-
}
-
//通过ThreadLocal类的get()方法返回线程局部变量值
-
public Double getAmount() {
-
return amount.get();
-
}
-
//通过ThreadLocal类的set()方法设置线程局部变量值
-
public void setAmount(Double amount) {
-
this.amount.set(amount);;
-
}
-
public String getName() {
-
return name;
-
}
-
public void setName(String name) {
-
this.name = name;
-
}
-
-
}
消费类 DailyConsmption
-
import java.util.Random;
-
-
public
class DailyConsmption implements Runnable {
-
-
private Account account;
-
Random random =
new Random();
-
-
public DailyConsmption(Account account) {
-
this.account = account;
-
}
-
-
@Override
-
public void run() {
-
//设置银行卡存款
-
account.setAmount((
double)random.nextInt((
2000)+
100));
-
System.out.println(account.getName()+
"的"+Thread.currentThread().getName()+
"银行卡,存款"+account.getAmount()+
"元");
-
//声明消费金额变量 comsumptionAmount
-
double consumptionAmount =
0.0;
-
//声明保存余额的变量
-
double balance =
0.0;
-
//模拟账户消费5次
-
for (
int i =
0; i <
5; i++) {
-
try {
-
Thread.sleep(
500);
-
}
catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
//随机生成一个消费金额
-
consumptionAmount = random.nextInt(((
100)+
1));
-
//消费完成之后的金额
-
balance = account.getAmount() - consumptionAmount;
-
if (balance >=
0) {
-
System.out.println(account.getName()+
"的"+Thread.currentThread().getName()+
"银行卡消费了"+account.getAmount()+
"元,余额"+balance+
"元");
-
account.setAmount(balance);
-
}
else {
-
System.out.println(account.getName()+
"的"+Thread.currentThread().getName()+
"银行卡余额只剩"+account.getAmount()+
"元,不够支付"+consumptionAmount+
"元");
-
break;
-
}
-
}
-
}
-
-
}
测试类 TestConsmption
-
-
public
class TestConsmption {
-
public static void main(String[] args) {
-
//实例化account对象
-
Account account =
new Account(
"张三");
-
//实例化Runnable对象
-
DailyConsmption consmption =
new DailyConsmption(account);
-
//创建并启动两条线程
-
new Thread(consmption,
"6222 5555 0022 2200").start();
-
new Thread(consmption,
"6222 5555 8899 1177").start();
-
}
-
-
}
转载:https://blog.csdn.net/weixin_44893902/article/details/108815806
查看评论