多執行緒銀行存取款
package cn.foresee.thread;
/**
* @Title: yoyogaosong
* @Description:
* @author: YOYO
* @Date: 2018-12-06 上午 11:22
* @Version: 1.0.0
*/
public class SaveThread extends Thread {
//模擬使用者賬戶
private Account account;
//當前存錢執行緒希望存的錢數
private double saveAccount;
public SaveThread(String name, Account account, double saveAccount){
super(name);
this.account = account;
this.saveAccount = saveAccount;
}
public void run() {
synchronized (account) {
System.out.println(getName() + " 存錢成功!存進鈔票:"
+ saveAccount+" 餘額為:" + account.getBalance());
account.setBalance(account.getBalance() + saveAccount);
}
}
}
package cn.foresee.thread;
/**
* @Title: yoyogaosong
* @Description:
* @author: YOYO
* @Date: 2018-12-06 上午 10:13
* @Version: 1.0.0
*/
public class DrawThread extends Thread {
//模擬使用者賬戶
private Account account ;
//當前取錢執行緒希望取的錢數
private double drawAccount ;
public DrawThread(String name ,Account account ,double drawAccount){
super(name);
this.account = account;
this.drawAccount = drawAccount;
}
public void run() {
synchronized (account) {
if (account.getBalance() >= drawAccount) {
System.out.println(getName() + " 取錢成功!吐出鈔票:" + drawAccount+" 餘額為:" + account.getBalance());
account.setBalance(account.getBalance() - drawAccount);
} else {
System.out.println(getName() + " 取錢失敗!餘額為:"+account.getBalance());
}
}
}
}
package cn.foresee.thread; /** * @Title: yoyogaosong * @Description: * @author: YOYO * @Date: 2018-12-06 上午 10:11 * @Version: 1.0.0 */ public class Account { private String accountNo ; private double balance ; public Account(String accountNo, double balance) { this.accountNo = accountNo; this.balance = balance; } public String getAccountNo() { return accountNo; } public void setAccountNo(String accountNo) { this.accountNo = accountNo; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Account account = (Account) o; if (Double.compare(account.balance, balance) != 0) return false; return accountNo != null ? accountNo.equals(account.accountNo) : account.accountNo == null; } @Override public int hashCode() { int result; long temp; result = accountNo != null ? accountNo.hashCode() : 0; temp = Double.doubleToLongBits(balance); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } }
package cn.foresee.thread;
public class Bank {
public static void main(String[] args) {
//卡號
Account account = new Account("VIP88888888", 0);
System.out.println("卡號: "+account.getAccountNo()+" 總資產: "+account.getBalance());
DrawThread drawThread1 = new DrawThread("李四", account, 200);
DrawThread drawThread2 = new DrawThread("王五", account, 400);
SaveThread saveThread1 = new SaveThread("老高", account, 300);
for (int i = 0; i < 5; i++) {
new Thread(drawThread1).start();
new Thread(drawThread2).start();
new Thread(saveThread1).start();
}
}
}