JAVA每日一题22

     题目:有两各线程accountant和cashier,他俩共同拥有一个帐本,他俩都可以使用saveOrTake(int mumber)对账本进行访问,会计使用saveOrTake方法时,向账本上写入存钱记录;出纳使用saveOrTake方法时,向账本写入取钱记录。因此,当会计正在使用saveOrTake方法时,出纳被禁止使用,反之也是这样。

    

class Bank  implements Runnable
{  
   int money=300;
   int time1,time2;
   Thread accountant,cashier;
   public Bank()
   { 
      accountant=new Thread(this);
      accountant.setName("会计");
      cashier=new Thread(this);
      cashier.setName("出纳");   
   }
  public void run()
   { 
       for(int i=1;i<=3;i++) //从周一到周三会计和出纳都要使用saveOrTake方法。
          {  
             if(Thread.currentThread()==accountant)  
              {
                 time1=i;
                 saveOrTake(30);  //accountant线程占有CUP资源期间调用了同步方法。
              }
             else if(Thread.currentThread()==cashier)  
              {
                 time2=i;
                 saveOrTake(30); //cashier线程占有CUP资源期间调用了同步方法。
              }
          }
   }
  public synchronized void saveOrTake(int number) //同步方法。
   {  
       if(Thread.currentThread()==accountant)    //如果是accountant占有CPU资源。
       {  
          System.out.printf("%s%d\n","今天是星期",time1);
          for(int i=1;i<=3;i++)        //accountant使用该方法存入90万,存入30万,稍歇一下,
            {                                          //这时cashier仍不能使用该方法,
                money=money+number;                   //因为accountant还没使用该方法。
                try {  
                       Thread.sleep(1000);         
                    }             
                catch(InterruptedException e)
                    {
                    }
                System.out.printf("%s,目前帐上有%d万圆\n","我是"+accountant.getName(),money);
            }
       }
      else if(Thread.currentThread()==cashier) //如果是cashier占有CPU资源。
      {    
           System.out.printf("%35s%d\n","今天是星期",time2);
           for(int i=1;i<=2;i++)        //cashier使用该方法取出30元,取出15元,稍歇一下,
            {                                       //这时accountant仍不能使用该方法,
               money=money-number/2;                //因为cashier还没使用完该方法。
               try  {
                      Thread.sleep(1000);    
                    }
               catch(InterruptedException e)
                    {
                    }
               System.out.printf("%35s,目前帐上有%d万圆\n","我是"+cashier.getName(),money);
            }
      }
   }
}
class Example
{
    public static void main(String args[ ])
    {
        Bank a=new Bank();
        a.accountant.start();
        a.cashier.start();
   }
}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值