class Account1 //帐户缓冲区
{ private String name;
private int value;
void put(int i) //欲存入金额i
{ value = value + i; //存入时,value值增加
}
int get(int i) //欲取金额i,返回实际取到金额
{ if (value>i)
value = value - i; //取走时,value值减少
else //帐户金额不够所取时
{ i = value;
value = 0; //取走全部所余金额
}
return i;
}
int howmatch() //查看帐户上现有金额
{ return value;
}
}
class Save1 extends Thread //存款线程
{ private Account1 a1;
private int amount;
public Save1(Account1 a1,int amount)
{ this.a1 = a1;
this.amount = amount;
}
public void run()
{ try
{ sleep(1); //花费时间
}
catch(InterruptedException e)
{ System.out.println(e);
}
int k = a1.howmatch();
a1.put(amount);
System.out.println("现有"+k+",存入"+amount+
",余额"+a1.howmatch());
}
public static void main (String args[])
{ Account1 a1 = new Account1();
(new Save1(a1,100)).start();
(new Save1(a1,200)).start();
(new Fetch1(a1,500)).start();
}
}
class Fetch1 extends Thread //取款线程
{ private Account1 a1;
private int amount;
public Fetch1(Account1 a1,int amount)
{ this.a1 = a1 ;
this.amount = amount;
}
public void run()
{ int k = a1.howmatch();
/*try
{ sleep(1); //花费时间
}
catch(InterruptedException e)
{ System.out.println(e);
}*/
System.out.println("现有"+k+",取走"+a1.get(amount)+
",余额"+a1.howmatch());
}
}
D:\myjava>javac Save1.java
D:\myjava>java Save1
现有0,取走0,余额0
现有0,存入100,余额100
现有100,存入200,余额300
{ private String name;
private int value;
void put(int i) //欲存入金额i
{ value = value + i; //存入时,value值增加
}
int get(int i) //欲取金额i,返回实际取到金额
{ if (value>i)
value = value - i; //取走时,value值减少
else //帐户金额不够所取时
{ i = value;
value = 0; //取走全部所余金额
}
return i;
}
int howmatch() //查看帐户上现有金额
{ return value;
}
}
class Save1 extends Thread //存款线程
{ private Account1 a1;
private int amount;
public Save1(Account1 a1,int amount)
{ this.a1 = a1;
this.amount = amount;
}
public void run()
{ try
{ sleep(1); //花费时间
}
catch(InterruptedException e)
{ System.out.println(e);
}
int k = a1.howmatch();
a1.put(amount);
System.out.println("现有"+k+",存入"+amount+
",余额"+a1.howmatch());
}
public static void main (String args[])
{ Account1 a1 = new Account1();
(new Save1(a1,100)).start();
(new Save1(a1,200)).start();
(new Fetch1(a1,500)).start();
}
}
class Fetch1 extends Thread //取款线程
{ private Account1 a1;
private int amount;
public Fetch1(Account1 a1,int amount)
{ this.a1 = a1 ;
this.amount = amount;
}
public void run()
{ int k = a1.howmatch();
/*try
{ sleep(1); //花费时间
}
catch(InterruptedException e)
{ System.out.println(e);
}*/
System.out.println("现有"+k+",取走"+a1.get(amount)+
",余额"+a1.howmatch());
}
}
D:\myjava>javac Save1.java
D:\myjava>java Save1
现有0,取走0,余额0
现有0,存入100,余额100
现有100,存入200,余额300