多線程 money

package com.phj20110824.Thread;

public class Account {
	private int balance;//餘額
	public  synchronized void withdraw(int money){
		
		balance=balance+money;
		
	}
	public  synchronized void getMoney(int money){
		//if(money<=this.balance){
			balance=balance-money;
			
		//}
		
	}
	public int getBalance(){
		return this.balance;
	}
}

package com.phj20110824.Thread;

public class GetMoney implements Runnable {
	private Account account;

	public GetMoney(Account account) {
		this.account = account;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < 10; i++) {
			this.account.getMoney(500);
		}

	}
}



package com.phj20110824.Thread;

public class AddMoney implements Runnable {
	private Account account;

	public AddMoney(Account account) {
		this.account = account;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < 10; i++) {
			this.account.withdraw(500);
		}

	}

}


package com.phj20110824.Thread;

public class AccountTest {
	public static void main(String[] args) {
		Account account = new Account();
		GetMoney getmoney = new GetMoney(account);
		AddMoney addmoney = new AddMoney(account);
		new Thread(getmoney).start();
		new Thread(addmoney).start();
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(account.getBalance());
	}
}




發佈了34 篇原創文章 · 獲贊 1 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章