简体   繁体   English

Thread.sleep()在java中同步

[英]Thread.sleep() with synchronization in java

when Thread.sleep(10000) is invoked current Thread will go to sleeping state. 当调用Thread.sleep(10000)时,当前Thread将进入休眠状态。 If Thread.sleep(10000) is invoked in synchronization method whether other thread can execute in that period? 如果在同步方法中调用Thread.sleep(10000)是否其他线程可以在该时间段内执行?

If you do Thread.sleep(10000) within a synchronized method or block you do not release the lock. 如果在同步方法或块中执行Thread.sleep(10000)则不释放锁。 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) 如果要等待条件发生的指定时间并释放对象锁,则需要使用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 如果我评论try catch块它将运行良好,因此同步块使用是有限的,直到m不使用这些try catch块

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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