java取款_java中的synchronized : 模拟取款

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();

}

}

执行效果:

d52e33864286a73e92de9e4dc7c870fa.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值