package account;
public class Bank {
public static void main(String[] argos){
Account a=new Account("12345678",100);
PutMoney p=new PutMoney(a);
GetMoney g=new GetMoney(a);
Thread tp=new Thread(p);
Thread tg=new Thread(g);
tp.start();
tg.start();
}
}
class Account {
String ID;
double balance;
Boolean b=true;
public Account(String strID,double b){
ID=strID;
balance=b;
}
public synchronized void putMoney(double money){
while(b){
try{
this.wait(10);
}catch(Exception e){
e.printStackTrace();};
System.out.println("账号:"+ID+"存入"+money);
balance +=money;
System.out.println("账号:"+ID+" 余额"+balance);
b=false;
notifyAll();
}
}
public synchronized void subMoney(double money){
while(!b){
System.out.println("账号:"+ID+" 要取出"+money);
if(balance>money){
balance -=money;
System.out.println("账号:"+ID+" 余额"+balance);
b=true;
notifyAll();
}
else{
System.out.println("余额不足,取款失败!");
b=true;
}
}
}}
class PutMoney implements Runnable{
Account a;
public PutMoney(Account a){
this.a=a;
}
public void run(){
for(int i=0;i<10;i++){
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();}
a.putMoney(Math.random()*1000);
}
}
}
class GetMoney implements Runnable{
Account a;
public GetMoney(Account a){
this.a=a;
}
public void run(){
for(int i=0;i<10;i++){
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();}
a.subMoney(Math.random()*1000);
}
}
}