Bank类,定义账号、账号余额属性,定义存款方法与取款方法并上同步
package person.xsc.practice;
import java.util.Scanner;
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();
// 修改余额
balance +=100;
// 修改账户余额
setBalance(balance);
// 输出存款后的账户余额
System.out.println(account+"存款后的账户余额为:" + balance);
}
public synchronized void drawAccount() {
// 获得当前的帐户余额
int balance = getBalance();
// 修改余额
balance = balance - 200;
// 修改帐户余额
setBalance(balance);
System.out.println(account+"取款后的帐户余额:" + balance);
}
}
取款线程
package person.xsc.practice;
//取款
public class DrawAccount implements Runnable{
Bank bank;
public DrawAccount(Bank bank){
this.bank=bank;
}
@Override
public void run() {
bank.drawAccount();
}
}
存款线程
package person.xsc.practice;
//存款
public class SaveAccount implements Runnable{
Bank bank;
public SaveAccount(Bank bank){
this.bank=bank;
}
public void run(){
bank.saveAccount();
}
}
测试类
package person.xsc.practice;
public class Test {
public static void main(String[] args) {
// 创建帐户,给定余额为1000
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(bank);
}
}
输出
1001存款后的账户余额为:1100
1001取款后的帐户余额:900
Bank [账号:1001, 余额:900]