package com.test;
public class TestAccount implements Runnable{
Account acc = new Account();
@Override
public void run() {
//可以取款5次
for (int i = 0; i < 5; i++) {
//取款
getM(1000);
if(acc.getMoney()==0){
System.out.println("帐户透支了");
break;
}
}
}
public void getM(int amt){
synchronized (acc) {
if(acc.getMoney()>=amt){
System.out.println(Thread.currentThread().getName()+"准备取款");
try {
Thread.sleep(1000); //0.5秒之后取款
} catch (InterruptedException e) {
e.printStackTrace();
}
acc.takeMoney(amt);
System.out.println(Thread.currentThread().getName()+"完成取款,余额为:"+acc.getMoney());
}else{
System.out.println("余额不足以支付"+Thread.currentThread().getName()
+"的取款,余额为:"+acc.getMoney());
}
}
}
}
package com.test;
public class Account {
private int money=5000;
//获取余额的方法
public int getMoney(){
return money;
}
//取款的方法
public void takeMoney(int ban){
money = money-ban;
}
}
package com.test;
public class Test {
public static void main(String[] args) {
TestAccount ta = new TestAccount();
new Thread(ta,"张三").start();
new Thread(ta,"张三老婆").start();
}
}