public class Account {
private String accountNo;
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
private double balance;
public double getBalance() {
return balance;
}
synchronized public void setBalance(double balance) {
this.balance = balance;
}
public Account(String accountNo, double balance) {
this.accountNo = accountNo;
this.balance = balance;
}
public int hasCode(){
return accountNo.hashCode();
}
synchronized public void draw(double drawAmount){
if(this.getBalance()>=drawAmount){
this.setBalance((this.getBalance()-drawAmount));
System.out.println("取钱成功.剩余"+this.getBalance());
}
else{
System.out.println("余额不足 剩余"+this.getBalance());
}
}
}
import java.util.concurrent.locks.ReentrantLock;
public class Account {
private final ReentrantLock lock = new ReentrantLock();
private String accountNo;
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
private double balance;
public double getBalance() {
return balance;
}
synchronized public void setBalance(double balance) {
this.balance = balance;
}
public Account(String accountNo, double balance) {
this.accountNo = accountNo;
this.balance = balance;
}
public int hasCode() {
return accountNo.hashCode();
}
synchronized public void draw(double drawAmount) {
lock.lock();
try {
if (this.getBalance() >= drawAmount) {
this.setBalance((this.getBalance() - drawAmount));
System.out.println("取钱成功.剩余" + this.getBalance());
} else {
System.out.println("余额不足 剩余" + this.getBalance());
}
} finally {
lock.unlock();
}
}
}
public class DrawThread extends Thread {
private Account account;
private double drawAccount;
public DrawThread(String name, Account account, double drawAmount) {
super(name);
this.account = account;
this.drawAccount = drawAmount;
}
public void run() {
account.draw(drawAccount);
}
}
public class MoneyMain {
public static void main(String[] args) throws Exception {
Account account = new Account("1234567", 1000);
new DrawThread("甲", account, 900).start();
new DrawThread("乙", account, 900).start();
}
}