银行的存取款可以分为存款和取款:
当去存款的时候会先显示账户信息,然后将存进去的钱和账户原有的钱数相加,返回存款之后账户信息;
当去取款的时候会先显示账户信息,然后将取钱数和账户里面的钱相对比,如果取钱数大于账户里面的钱,那就将账户里面的钱全部取出,如果取钱数小于账户的钱,那就吐出所取的钱数。
本例使用了线程来处理,而且使用了线程同步(synchronized)的知识点
一.首先先建立一个账户类:
class Account{
private String name;
private int value;
public int getMoney(int money){
if(money >= this.value){
this.value = 0;
}else{
this.value = this.value - money;
}
return money;
}
public void saveMoney(int money){
this.value = this.value + money;
}
public int searchMoney(){
return this.value;
}
public Account() {
super();
}
public Account(String name, int value) {
super();
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
class SaveAccount implements Runnable{
private Account a;
private int money;
public SaveAccount() {
super();
}
public SaveAccount(Account a, int money) {
super();
this.a = a;
this.money = money;
}
@Override
public void run() {
synchronized (a)
{
try {
int currentMoney = a.searchMoney();
Thread.sleep(1000);
a.saveMoney(money);
System.out.println("尊敬的客户:" + a.getName() + "您好! 您的账户余额" + currentMoney
+ "元,您存入" + this.money + "元,当前账户余额为:" + a.searchMoney() + "元");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
三.建立一个取钱线程,包含取钱的操作:
class GetMoney implements Runnable{
private Account a;
private int money;
public GetMoney() {
super();
}
public GetMoney(Account a, int money) {
super();
this.a = a;
this.money = money;
}
@Override
public void run() {
synchronized (a)
{
try {
int currentMoney = a.searchMoney();
Thread.sleep(1000);
a.getMoney(money);
System.out.println("尊敬的客户:" + a.getName() + "您好! 您的账户余额" + currentMoney
+ "元,您取出" + this.money + "元,当前账户余额为:" + a.searchMoney() + "元");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
四.接下来是主函数调用:
public class ThreadTest6 {
public static void main(String[] args) {
Account account = new Account("Zhou",10000000);
SaveAccount sa = new SaveAccount(account, 10);
GetMoney gm =new GetMoney(account, 10000);
Thread t = new Thread(gm);
Thread t1 = new Thread(sa);
t.start();
t1.start();
}
}
五.代码运行截图: