多线程模拟银行取款业务
public class Account {
int id; //编号
double balance;//余额
public Account(int id, double balance) {
this.id = id;
this.balance = balance;
}
public Account() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void getMoney(double money){
synchronized ("1") {
if (money > this.getBalance()) { //对输入金额进行判断
System.out.println(Thread.currentThread().getName()+"您的取款金额为" + money + "\t" + "您的余额为" + this.getBalance() + "\t" + "取款失败");
return;
} else {
double begin = this.getBalance();//取款之前的余额
double end = begin - money;//取款之后的余额
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setBalance(end);//更新余额
System.out.println(Thread.currentThread().getName()+"取款成功,余额为"+this.getBalance());
}
}
}
}
public class AccountThread extends Thread {
Account account=new Account();
public AccountThread(Account account){
this.account=account;
}
@Override
public void run() {
double money=17777;
account.getMoney(money);
}
}
public class AccountThreadText {
public static void main(String[] args) {
Account account=new Account(1,20000);
AccountThread t1=new AccountThread(account);
AccountThread t2=new AccountThread(account);
t1.setName("客户1\t");
t2.setName("客户2\t");
t1.start();
t2.start();
}
}
客户1 取款成功,余额为2223.0
客户2 您的取款金额为17777.0 您的余额为2223.0 取款失败
客户1 取款成功,余额为10000.0
客户2 取款成功,余额为0.0