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());
}
}