when Thread.sleep(10000) is invoked current Thread will go to sleeping state. If Thread.sleep(10000) is invoked in synchronization method whether other thread can execute in that period?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
If you do Thread.sleep(10000)
within a synchronized method or block you do not release the lock. Hence if other Threads are waiting on that lock they won't be able to execute.
If you want to wait for a specified amount of time for a condition to happen and release the object lock you need to use Object.wait(long)
回答2:
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);
}
I made this method as synchronized,I run two separate threads which are running concurrently & executing this method producing unwanted results!! If i comment the try catch block it will run fine,So is the synchronized block use is limited till m not using these try catch block