synchronized可以解决原子性问题?

欢迎纠正!

使用银行取钱来实现线程并发安全问题!
在没有加锁之前!出现原子性 可见性问题! 线程出错

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
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是汤圆丫

怎么 给1分?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值