Thread.sleep() with synchronization in java

三世轮回 提交于 2019-12-21 05:51:39

问题


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



来源:https://stackoverflow.com/questions/4479443/thread-sleep-with-synchronization-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!