package com.imooc.bank;
//银行类
public class Bank {
private String account;
private int balance;
public Bank(String account, int balance) {
this.account = account;
this.balance = balance;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Bank [账号:"+account+", 余额:"+balance+"]";
}
//存款
public synchronized void saveAccount() {
int balance = getBalance();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
balance += 100;
setBalance(balance);
System.out.println("存款后的账户余额为:"+balance);
}
//取款
public void drawAccount() {
int balance = getBalance();
balance -= 200;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setBalance(balance);
System.out.println("取款后的账户余额为:"+balance);
}
}
package com.imooc.bank;
//取款线程
public class DrawAccount implements Runnable{
private Bank bank;
public DrawAccount(Bank bank) {
this.bank = bank;
}
@Override
public void run() {
bank.drawAccount();
}
}
package com.imooc.bank;
//存款线程
public class SaveAccount implements Runnable{
private Bank bank;
public SaveAccount(Bank bank) {
this.bank = bank;
}
@Override
public void run() {
bank.saveAccount();
}
}
package com.imooc.bank;
//测试类
public class Test {
public static void main(String[] args) {
Bank bank = new Bank("1001", 1000);
SaveAccount sa = new SaveAccount(bank);
DrawAccount da = new DrawAccount(bank);
Thread save = new Thread(sa);
Thread draw = new Thread(da);
save.start();
draw.start();
try {
save.join();
draw.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
//加join是为了让下面这条语句最后输出
System.out.println(bank);
}
}
为啥会产生这样的输出?
取款后的账户余额为:800
存款后的账户余额为:1100
Bank [账号:1001, 余额:1100]
如果我把saveAccount方法也用synchronized修饰的话就会正常输出。
存款后的账户余额为:1100
取款后的账户余额为:900
Bank [账号:1001, 余额:900]
是sleep的原因导致调用这个public synchronized void saveAccount() 方法的线程被阻塞, 然后被别的线程占用了cpu吗?
不是说synchronized修饰的方法调用过程中不会被别的线程打断吗?
求大神解答!!