2010-12-18 76 views

回答

15

如果你在同步方法或块内做Thread.sleep(10000)不要释放锁。因此,如果其他线程正在等待该锁,它们将无法执行。

如果你想等待指定的时间量的情况发生,并释放你需要使用Object.wait(long)

0
private synchronized void deduct() 
{ 
    System.out.println(Thread.currentThread().getName()+ " Before Deduction "+balance); 
    if(Thread.currentThread().getName().equals("First") && balance>=50) 
    { 
     System.out.println(Thread.currentThread().getName()+ " Have Sufficent balance will sleep now "+balance); 
     try 
     { 
      Thread.currentThread().sleep(100); 
     } 
     catch(Exception e) 
     { 
      System.out.println("ThreadInterrupted"); 
     } 
     balance = balance - 50; 
    } 
    else if(Thread.currentThread().getName().equals("Second") && balance>=100) 
    { 
     balance = balance - 100; 
    } 
     System.out.println(Thread.currentThread().getName()+ " After Deduction "+balance); 
    System.out.println(Thread.currentThread().getName()+ " "+balance); 
} 

我做出同步此方法的对象的锁,我运行两个单独的线程这正在同时运行&执行此方法产生不想要的结果! 如果我评论try catch块它会运行良好,所以是同步块的使用是有限的,直到米不使用这些尝试catch块