繁体   English   中英

Thread.sleep()在java中同步

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

当调用Thread.sleep(10000)时,当前Thread将进入休眠状态。 如果在同步方法中调用Thread.sleep(10000)是否其他线程可以在该时间段内执行?

如果在同步方法或块中执行Thread.sleep(10000)则不释放锁。 因此,如果其他线程正在等待该锁定,则它们将无法执行。

如果要等待条件发生的指定时间并释放对象锁,则需要使用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);
}

我使这个方法同步,我运行两个独立运行的线程并执行此方法产生不需要的结果! 如果我评论try catch块它将运行良好,因此同步块使用是有限的,直到m不使用这些try catch块

暂无
暂无

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

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