package 线程同步;
public class Account {
// 封装账号编号、账号余额的两个成员变量
private String accountNo;
private double balance;
public Account() {
}
// 构造器
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;
}
// 下面两个方法根据accountNo来重写hashCode()和equals()方法
public int hashCode() {
return accountNo.hashCode();
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj != null && (obj.getClass() == Account.class)) {
Account target = (Account) obj;
return target.getAccountNo().equals(accountNo);
}
return false;
}
}
package 线程同步;
public class DrawThread extends Thread {
// 模拟用户账号
private Account account;
// 当前取钱线程所希望取的钱数
private double drawAmount;
public DrawThread(String name, Account account, double drawAmount) {
super(name);
this.account = account;
this.drawAmount = drawAmount;
}
// 当多个线程修改同一个共享数据时,将涉及到数据安全问题
public void run() {
// 使用account作为同步监视器,任何线程进入下面同步进程块之前
// 必须先获得对account账户的锁定---其他线程无法获得说、锁,也无法修改它
// 这种做法符合:“加锁->修改->释放锁”的逻辑
synchronized (account) {
// 账户余额大于或等于取钱数
if (account.getBalance() >= drawAmount) {
// 吐出钞票
System.out.println(getName() + "取钱成功!吐出钞票:" + drawAmount);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 修改余额
account.setBalance(account.getBalance() - drawAmount);
System.out.println("\t余额为:" + account.getBalance());
}
else{
System.out.println(getName()+"取钱失败!余额不足!");
}
}
//同步代码块结束,该线程释放同步锁
}
}
package 线程同步;
public class Test {
public static void main(String[] args) {
//创建一个账户
Account acct = new Account("123456",1000);
//模拟两个线程对同一个账户取钱
new DrawThread("张三",acct,800).start();;
new DrawThread("李四",acct,800).start();;
}
}
运行结果: