java实现存取钱过程(synchronized关键字的应用)

package com.stu.bankModel;




/**
 * 线程安全测试
 * 通过存取钱案列检验
 * @author jj
 *
 */
public class ThreadSafeTest {
	public static void main(String[] args) {
		Account account = new Account("张山", 5000D);
		
		DrawOperation draw = new DrawOperation(account, 1000D);
		for(int i=0;i<50;i++){
			new Thread(draw).start();
		}
		
		SaveOperation save = new SaveOperation(account, 500D);
		for(int i=0;i<50;i++){
			new Thread(save).start();
		}
	}
}


/**
 * 账户类
 * @author jj
 *
 */
class Account{
	private String name;
	private Double balance;
	public Account(String name, Double balance) {
		super();
		this.name = name;
		this.balance = balance;
	}
	public Account() {
		super();
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Double getBalance() {
		return balance;
	}
	public void setBalance(Double balance) {
		this.balance = balance;
	}
	
	/**
	 * 存钱
	 */
	public void Save(Double money){
		this.balance = this.balance + money;
		System.out.println(this.name + "存入金额:" +money+"\t余额:"+this.balance);
	}
	
	/**
	 * 取钱
	 */
	public void Draw(Double money){
		if(this.balance>=money){
			this.balance = this.balance - money;
			System.out.println(this.name + "取款金额:" +money+"\t余额:"+this.balance);
		}else{
			System.out.println("余额不足!当前余额:"+this.balance);
		}
	}
}


/**
 * 账户操作类(取款)
 * @author jj
 *
 */
class DrawOperation implements Runnable{
	private Account account;//账户
	private Double drawMoney;//取款金额
	public DrawOperation(Account account, Double drawMoney){
		this.account = account;
		this.drawMoney = drawMoney;
	}
	@Override
	public void run() {
		synchronized(account){
			try {
				account.Draw(drawMoney);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}


/**
 * 存款操作
 * @author jj
 *
 */
class SaveOperation implements Runnable{
	private Account account;
	private Double saveMoney;
	public SaveOperation(Account account, Double saveMoney){
		this.account = account;
		this.saveMoney = saveMoney;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		synchronized (account) {
			try {
				account.Save(saveMoney);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}
推荐一篇关于关键字synchronized的博客: https://blog.csdn.net/luoweifu/article/details/46613015
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值