简体   繁体   中英

Thread.sleep() with synchronization in java

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?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM