账户类
取钱方法在账户里,属于账户对象
public class Account {
private String accID;
private double balance;
public Account() {
}
public Account(String accID, double balance) {
this.accID = accID;
this.balance = balance;
}
public String getAccID() {
return accID;
}
public void setAccID(String accID) {
this.accID = accID;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void withdraw(double money){
String name = Thread.currentThread().getName();
if (this.balance >= money){
System.out.println(name+ " withdraw succeed, amount is:"+money);
this.balance -= money;
System.out.println("After "+name+"'s withdraw, the balance changed to: "+ balance);
}else {
System.out.println("Sorry, your amount is over your balance.");
}
}
}
取钱线程类
创建线程,把线程的run方法重写,里头调用账户的取钱方法
public class withdrawThread extends Thread {
private Account acc;
public withdrawThread(Account acc,String name) {
super(name);
this.acc = acc;
}
@Override
public void run() {
acc.withdraw(100000.0);
}
}
执行体
这个账户的构造器里写一个账户ID的成员变量就意思意思,不影响本例
public class ThreadSecurityDemo1 {
public static void main(String[] args) {
Account acc = new Account("MTU_010203",100000);
new withdrawThread(acc,"Peter").start();
new withdrawThread(acc,"Diana").start();
}
}