第四周作业

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. class BankAccount  
  2. {  
  3.     private static int amount=2000;  
  4.     public void despoit(int m)  
  5.     {  
  6.         amount =amount + m;  
  7.         System.out.println("小明存入["+m +"元]");  
  8.     }  
  9.     public void withdraw(int m)  
  10.     {  
  11.         amount =amount-m;  
  12.         System.out.println("张新取走["+m +"元]");  
  13.         if (amount <0)  
  14.             System.out.println("***余额不足!***");  
  15.     }  
  16.     public int balance()  
  17.     {  
  18.         return amount;  
  19.     }  
  20. }  
  21. class Customer extends Thread  
  22. {  
  23.     String name;  
  24.     BankAccount bs;  
  25.     public Customer(BankAccount b,String s)  
  26.     {  
  27.         name =s;  
  28.         bs =b;  
  29.     }  
  30.     public synchronized static void cus (String name, BankAccount bs)  
  31.     {  
  32.         if(name.equals("小明"))  
  33.         {  
  34.             try  
  35.             {  
  36.                 for(int i =0;i<6;i++)  
  37.                 {  
  38.                     Thread.currentThread();  
  39.                     Thread.sleep((int)(Math.random()*300));  
  40.                     bs.despoit(1000);             
  41.                 }  
  42.             }  
  43.             catch(InterruptedException e)  
  44.             {}  
  45.         }  
  46.         else  
  47.         {  
  48.             try  
  49.             {  
  50.                 for(int i=0;i<6;i++)  
  51.                 {  
  52.                     Thread.currentThread();  
  53.                     Thread.sleep((int)(Math.random()*300));  
  54.                     bs.withdraw(1000);  
  55.                 }  
  56.             }  
  57.             catch(InterruptedException e)  
  58.             {}  
  59.         }         
  60.     }  
  61.     public void run()  
  62.     {  
  63.         cus(name,bs);  
  64.     }  
  65. }  
  66. public class AccountTest1  
  67. {  
  68.     public static void main(String args[])throws InterruptedException  
  69.     {  
  70.         BankAccount bs =new BankAccount();  
  71.         Customer customer1=new Customer(bs,"小明");  
  72.         Customer customer2=new Customer(bs,"张新");  
  73.         Thread t1 =new Thread(customer1);  
  74.         Thread t2 =new Thread(customer2);  
  75.         t1.start();  
  76.         t2.start();  
  77.         Thread.currentThread();  
  78.         Thread.sleep(500);  
  79.     }  
  80. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值