java中的synchronized : 模拟取款

时间:2023-12-16 20:15:38

1.定义账户类:

public class Account {
private int balance = 500;

public int getBalance() {
return balance;
}

public void setBalance(int balance) {
this.balance = balance;
}

//取款
public void withdraw (int amount){
balance = balance - amount;
}

}

------------------------------------

2.定义取款类:

public class TestAmount implements Runnable {
private Account acct = new Account();

public void run() {
for (int i = 0; i < 5; i++) {
makeWithdrawal(100);

if(acct.getBalance() < 0){
System.out.println("账户透支了!");
}
}

}

private synchronized void makeWithdrawal(int amt){
if(acct.getBalance() >= amt){
System.out.println(Thread.currentThread().getName()+"准备取款");
try {
Thread.sleep(500); //0.5秒后实现取款
} catch (Exception e) {
}
// 如果钱足够,则取款
acct.withdraw(amt);
System.out.println(Thread.currentThread().getName()+"完成取款");
}else{
System.out.println("余额不足以支付: "+Thread.currentThread().getName()+"的取款,余额为:"+acct.getBalance());
}
}

}

-----------------------------------------------

3.定义测试类:

public class TestWithDraw {
public static void main(String[] args) {
TestAmount tc= new TestAmount();
Thread one = new Thread(tc);
Thread two = new Thread(tc);
one.setName("张三");
two.setName("李四");

one.start();
two.start();

}

}

执行效果:

java中的synchronized  :  模拟取款