java中带有同步的Thread.sleep()
当调用Thread.sleep(10000)时,当前线程将进入睡眠状态。java中带有同步的Thread.sleep(),java,multithreading,synchronized,Java,Multithreading,Synchronized,当调用Thread.sleep(10000)时,当前线程将进入睡眠状态。 如果在同步方法中调用了Thread.sleep(10000),那么其他线程是否可以在此期间执行?如果在同步方法或块中执行Thread.sleep(10000),则不要释放锁。因此,如果其他线程正在等待该锁,它们将无法执行 如果要等待指定的时间以使某个条件发生并释放对象锁,则需要使用object.wait(long) 我使这个方法成为同步的,我运行两个独立的线程同时运行&执行这个方法会产生不想要的结果!! 如果我对try-c
如果在同步方法中调用了Thread.sleep(10000),那么其他线程是否可以在此期间执行?如果在同步方法或块中执行Thread.sleep(10000),则不要释放锁。因此,如果其他线程正在等待该锁,它们将无法执行 如果要等待指定的时间以使某个条件发生并释放对象锁,则需要使用
object.wait(long)
我使这个方法成为同步的,我运行两个独立的线程同时运行&执行这个方法会产生不想要的结果!!
如果我对try-catch块进行注释,它将正常运行,因此在我不使用这些try-catch块之前,同步块的使用是有限的
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);
}