ATM 中代码:
public class ATM implements Runnable{
private int mun;
static Bank bank;
static{
bank = new Bank(1000);
}
public ATM(int mun) {
super();
this.mun = mun;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getMoney();
}
//synchronized加在方法上,则该方法是同步方法 等同于synchronized(this){ ... }
public synchronized void getMoney(){
//下面的这种是同步块
synchronized(this){
//三个线程同时获得bank.getMoney()==1000
if(bank.getMoney()>= this.mun){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bank.setMoney(bank.getMoney()-this.mun);
System.out.println("取钱成功"+Thread.currentThread().getName());
}else{
System.out.println("余额不足");
}
}
}
}
Bank中代码:
public class Bank {
private int Money;
public Bank(int money) {
super();
Money = money;
}
public int getMoney() {
return Money;
}
public void setMoney(int money) {
Money = money;
}
}
Test中代码:
public class Test03 {
public static void main(String[] args) {
ATM a01 = new ATM(700);
ATM a02 = new ATM(600);
ATM a03 = new ATM(500);
Thread th01 = new Thread(a01,"甲");
Thread th02 = new Thread(a02,"乙");
Thread th03 = new Thread(a03,"丙");
th01.start();
th02.start();
th03.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ATM.bank.getMoney());
}
}
输出的结果是三个都取到了钱,ATM剩下-800?
怎样让第一个取得到钱,二三个输出余额不足,ATM剩下300
------最佳解决方案--------------------------------------------------------
synchronized(this)
改成同步bank就可以了
synchronized(bank)