class Account2
{
private String accountNo;
private double balance;
private boolean flag=false;
public Account2() {}
public Account2(String accountNo,double balance)
{
this.accountNo=accountNo;
this.balance=balance;
}
public void setAccountNo(String n)
{
accountNo=n;
}
public String getAccountNo()
{
return accountNo;
}
public double getBalance()
{
return this.balance;
}
public synchronized void draw(double drawAmount)
{
try
{
if(!flag)
{
wait();
}
else
{
System.out.println(Thread.currentThread().getName()+"取钱:"+drawAmount);
balance-=drawAmount;
System.out.println("账户余额为:"+balance);
flag=false;
notifyAll();
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
public synchronized void depoist(double depoistAmount)
{
try
{
if(flag)
{
wait();
}
else
{
System.out.println(Thread.currentThread().getName()+"存钱:"+depoistAmount);
balance+=depoistAmount;
System.out.println("账户余额为:"+balance);
flag=true;
notifyAll();
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
public int hashCode()
{
return accountNo.hashCode();
}
public boolean equals(Object obj)
{
if(this==obj)
return true;
if(obj!=null&& obj.getClass()==Account1.class)
{
Account1 target=(Account1)obj;
return target.getAccountNo().equals(accountNo);
}
return false;
}
}
class DrawThread1 extends Thread
{
private Account2 account;
private double drawAmount;
public DrawThread1(String name,Account2 account,double drawAmount)
{
super(name);
this.account=account;
this.drawAmount=drawAmount;
}
public void run()
{
for(int i=0;i<100;i++)
{
account.draw(drawAmount);
}
}
}
class DepoistThread extends Thread
{
private Account2 account;
private double depoistAmount;
public DepoistThread(String name,Account2 account,double depoistAmount)
{
super(name);
this.account=account;
this.depoistAmount=depoistAmount;
}
public void run()
{
for(int i=0;i<100;i++)
{
account.draw(depoistAmount);
}
}
}
public class DrawSaveDemo {
public static void main(String[] args) {
Account2 acct=new Account2("1234567",0);
new DrawThread1("取钱者",acct,800).start();
new DepoistThread("存款者甲",acct,800).start();
new DepoistThread("存款者乙",acct,800).start();
new DepoistThread("存款者丙",acct,800).start();
}
}