簡體   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