黑马程序员技术交流社区

标题: 模拟线程问题 [打印本页]

作者: 感觉很cooooool    时间: 2015-12-27 11:27
标题: 模拟线程问题
用多线程模拟向银行存钱的过程,两个人,每次存500元,存三次。



作者: 在下叶良辰    时间: 2015-12-27 11:27
//账户类 public class Acount {  private int money;  public Acount(int money){   this.money=money;  }  public synchronized void getMoney(int money){   while(this.money<money){//注意这个地方必须用while循环,因为即便再存入钱也有可能比取的要少    System.out.println("取款:"+money+" 余额:"+this.money+" 余额不足,正在等待存款......");    try{ wait();} catch(Exception e){}   }   this.money=this.money-money;   System.out.println("取出:"+money+" 还剩余:"+this.money);   //notify();  }  public synchronized void setMoney(int money){   /*while(this.money+money>10000){    try{ System.out.println("余额:"+this.money+"存款:"+money+" 该帐户最多存款10000 等待取款...");wait();}catch(Exception e){}   }*/   try{ Thread.sleep(10);}catch(Exception e){}   this.money=this.money+money;   System.out.println("新存入:"+money+" 共计:"+this.money);   notify();  }  public static void main(String args[]){   Acount Acount=new Acount(0);   Bank b=new Bank(Acount);   Consumer c=new Consumer(Acount);   new Thread(b).start();   new Thread(c).start();  } } //存款类 class Bank implements Runnable {  Acount Acount;  public Bank(Acount Acount){   this.Acount=Acount;  }  public void run(){   while(true){    int temp=(int)(Math.random()*1000);    Acount.setMoney(temp);       }  }   } //取款类 class Consumer implements Runnable {  Acount Acount;  public Consumer(Acount Acount){   this.Acount=Acount;  }  public void run(){   while(true){        int temp=(int)(Math.random()*1000);    Acount.getMoney(temp);   }  } }




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2