欢迎纠正!
使用银行取钱来实现线程并发安全问题!
在没有加锁之前!出现原子性 可见性问题! 线程出错
synchronized可以解决原子性问题!
二个synchronized锁,就不能产生互斥!!就会失效!出现安全并发问题!
要同一个锁 才能!!保证锁的互斥!!保证线程安全执行!
所以使用在取钱之前 加入 synchronized的!!!
public class AccountTest {
public static void main(String[] args) throws InterruptedException {
Account account=new Account("123456789", "123", 5000D); //账户
Wife wife=new Wife(account);
HashBand hashband=new HashBand(account);
Thread.sleep(100L);
Thread t=new Thread(wife);
Thread t2=new Thread(hashband);
t.start();
t2.start();
}
}
class Person{}
class HashBand extends Person implements Runnable{
Account account ;
public HashBand(Account account) {
this.account=account;
}
@Override
public void run() {
account.drowWith("123456789", "123", 2200D);
}
}
/**
* 妻子类
* @author 戴尔
*
*/
class Wife extends Person implements Runnable{
Account account;
public Wife(Account account) {
this.account = account;
}
@Override
public void run() {
account.drowWith("123456789", "123", 2200D);
}
}
/***
*
* 银行类
* @author 戴尔
*
*/
class Account {
String carNode;
String password;
Double money;
public Account(String carNode, String password, Double money) {
super();
this.carNode = carNode;
this.password = password;
this.money = money;
}
/**synchronized可以解决原子性问题,
*
*
* 取钱方法
*/
public synchronized void drowWith(String kahao,String mima,Double mon) {
System.out.println("开始效验开始");
if (kahao.equals(this.carNode) && mima.equals(this.password)) {
System.out.println("验证成功!开始操作");
if (mon<this.money) {
System.out.println("开始取钱操作");
this.money=this.money-mon;
System.out.println("余额为:"+money+"元");
}else {
System.out.println("余额不足");
}
}else {
System.out.println("用户名或者密码错误");
}
}
}
结果:
开始效验开始
验证成功!开始操作
开始取钱操作
开始效验开始
验证成功!开始操作
开始取钱操作
余额为:2800.0元
余额为:600.0元