public class Test8
{
   public static void main(String[] args)
   {
    Bank bank = new Bank();
    ThreadOne t1 = new ThreadOne(bank);
    bank = new Bank();
    ThreadOne t2 = new ThreadOne(bank);
    
    t1.start();
    t2.start();
   }
}
class Bank
{
      private static int money = 1000;;
      
      public int getMoney(int number)
      {
       if(number < 0)
       {
       return -1;
       }
       else if(number > money)
       {
       return -2;
       }
       else if(money < 0)
       {
       return -3;
       }
       else
       {
       try
   {
   Thread.sleep(1000);
   }
   catch (InterruptedException e)
   {
   e.printStackTrace();
   }
      money -= number;
      
             System.out.println("money left : " + money);
             return number;
       }
       
      }
}
class ThreadOne extends Thread
{
      private Bank bank;
      
      public ThreadOne(Bank bank)
      {
       this.bank = bank;
      }
      public void run()
      {
       System.out.println(bank.getMoney(800));
      }
}结果:meney left : 200
      meney left : 200
      800
      800
这个结果作何解释!

解决方案 »

  1.   

    bank = new Bank();
    把这句干掉能看到一个效果;再把线程的try-catch干掉又是一个效果,不知道你想要哪个啊
      

  2.   

    你没有给线程的方法加锁,出现这样的状况很正常的。
    这样说吧,
    一个线程开始运算,取出数据,提出200,未提交(就是还未对数字进行修改)
    另外一个线程也提出200,但是已经提交了,这样返回是800,
    这是第一个线程提交是不是也应该提交800呢?
    你在线程运行的方法后面加上
    Thread.currentThread().getName();
    看看线程名就知道了。
    在get和set方法前面加锁
    synchronized