1. 程式人生 > >java實現存取錢過程(synchronized關鍵字的應用)

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