Thread.sleep() with synchronization in java

2019-04-01 13:24发布

问题:

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