1. 程式人生 > >Java執行緒之銀行存取款

Java執行緒之銀行存取款

銀行的存取款可以分為存款和取款:

當去存款的時候會先顯示賬戶資訊,然後將存進去的錢和賬戶原有的錢數相加,返回存款之後賬戶資訊;

當去取款的時候會先顯示賬戶資訊,然後將取錢數和賬戶裡面的錢相對比,如果取錢數大於賬戶裡面的錢,那就將賬戶裡面的錢全部取出,如果取錢數小於賬戶的錢,那就吐出所取的錢數。

本例使用了執行緒來處理,而且使用了執行緒同步(synchronized)的知識點

一.首先先建立一個賬戶類:

class Account{
	private String name;
	private int value;
	public int getMoney(int money){
		if(money >= this.value){
			this.value = 0;
		}else{
			this.value = this.value - money;
		}
		return money;
	}
	public void saveMoney(int money){
		this.value = this.value + money;
	}
	public int searchMoney(){
		return this.value;
	}
	public Account() {
		super();
	}
	public Account(String name, int value) {
		super();
		this.name = name;
		this.value = value;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getValue() {
		return value;
	}
	public void setValue(int value) {
		this.value = value;
	}

}
二.建立一個存錢的執行緒,處理存錢的操作:
class SaveAccount implements Runnable{
	private Account a;
	private int money;
	
	public SaveAccount() {
		super();
	}

	public SaveAccount(Account a, int money) {
		super();
		this.a = a;
		this.money = money;
	}

	@Override
	public void run() {
		
		synchronized (a) 
		{
			try {
				int currentMoney = a.searchMoney();
				Thread.sleep(1000);
				a.saveMoney(money);
				System.out.println("尊敬的客戶:" + a.getName() + "您好! 您的賬戶餘額" + currentMoney 
						+ "元,您存入" + this.money + "元,當前賬戶餘額為:" + a.searchMoney() + "元");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		
		
		}
	}
	
}

三.建立一個取錢執行緒,包含取錢的操作:
class GetMoney implements Runnable{
	private Account a;
	private int money;
	
	public GetMoney() {
		super();
	}

	public GetMoney(Account a, int money) {
		super();
		this.a = a;
		this.money = money;
	}

	@Override
	public void run() {
		
		synchronized (a) 
		{
			try {
				int currentMoney = a.searchMoney();
				Thread.sleep(1000);
				a.getMoney(money);
				System.out.println("尊敬的客戶:" + a.getName() + "您好! 您的賬戶餘額" + currentMoney 
						+ "元,您取出" + this.money + "元,當前賬戶餘額為:" + a.searchMoney() + "元");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}

四.接下來是主函式呼叫:
public class ThreadTest6 {
	public static void main(String[] args) {
		Account account = new Account("Zhou",10000000);
		SaveAccount sa = new SaveAccount(account, 10);
		GetMoney gm =new GetMoney(account, 10000);
		Thread t = new Thread(gm);
		Thread t1 = new Thread(sa);
		t.start();
		t1.start();
	}
}

五.程式碼執行截圖: