Thread.sleep () with java sync

when calling Thread.sleep (10000) current Thread will go into sleep state. If Thread.sleep (10000) is called in the synchronization method, can another thread execute during this period?

+3
source share
2 answers

If you are executing Thread.sleep(10000)as part of a synchronized method or block not , release the lock. Therefore, if other threads are waiting for this lock, they will not be able to execute.

If you want to wait a certain amount of time for a condition to occur and release an object lock, you need to use Object.wait(long)

+15
source
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);
}

, , , !! catch try, , , m catch try

0

Source: https://habr.com/ru/post/1781048/


All Articles