class Account{
private static int balance=50;
public int getBalance(){
return balance;
}
public void withdraw(int amt){
balance=balance-amt;
}
}
public class fetchMoney implements Runnable {
private Account count=new Account();
public static void main(String[]args){
fetchMoney samin=new fetchMoney();
fetchMoney wang=new fetchMoney();
Thread one=new Thread(samin);
Thread two=new Thread(wang);
one.setName("samin");
two.setName("wang");
one.start();
two.start();
}
public synchronized void run(){
for(int x=0;x<5;x++){
System.err.println(Thread.currentThread().getName()+"-------- begin withdraw "+count.getBalance());
makeWithdraw(10);
System.err.println(Thread.currentThread().getName()+"-------- withdraw ok "+count.getBalance());
if(count.getBalance()<0){
System.err.println("account is overdrawn~!");
}
}
}
private synchronized void makeWithdraw(int amt){
if(count.getBalance()>=amt){
System.out.println(Thread.currentThread().getName()+" is going to withdraw "+count.getBalance());
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
count.withdraw(amt);
System.out.println(Thread.currentThread().getName()+" is done withdraw "+count.getBalance());
}
else{
System.out.println(Thread.currentThread().getName()+
" sorry,not enough money "+count.getBalance());
}
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货