Difference between wait() and sleep()

前端 未结 30 3137
無奈伤痛
無奈伤痛 2020-11-22 00:24

What is the difference between a wait() and sleep() in Threads?

Is my understanding that a wait()-ing Thread is still in runni

30条回答
  •  天涯浪人
    2020-11-22 00:37

    There are some difference key notes i conclude after working on wait and sleep, first take a look on sample using wait() and sleep():

    Example1: using wait() and sleep():

    synchronized(HandObject) {
        while(isHandFree() == false) {
            /* Hand is still busy on happy coding or something else, please wait */
            HandObject.wait();
        }
    }
    
    /* Get lock ^^, It is my turn, take a cup beer now */
    while (beerIsAvailable() == false) {
        /* Beer is still coming, not available, Hand still hold glass to get beer,
           don't release hand to perform other task */
        Thread.sleep(5000);
    }
    
    /* Enjoy my beer now ^^ */
    drinkBeers();
    
    /* I have drink enough, now hand can continue with other task: continue coding */
    setHandFreeState(true);
    synchronized(HandObject) {
        HandObject.notifyAll();
    }
    

    Let clarity some key notes:

    1. Call on:
      • wait(): Call on current thread that hold HandObject Object
      • sleep(): Call on Thread execute task get beer (is class method so affect on current running thread)
    2. Synchronized:
      • wait(): when synchronized multi thread access same Object (HandObject) (When need communication between more than one thread (thread execute coding, thread execute get beer) access on same object HandObject )
      • sleep(): when waiting condition to continue execute (Waiting beer available)
    3. Hold lock:
      • wait(): release the lock for other object have chance to execute (HandObject is free, you can do other job)
      • sleep(): keep lock for at least t times (or until interrupt) (My job still not finish, i'm continue hold lock and waiting some condition to continue)
    4. Wake-up condition:
      • wait(): until call notify(), notifyAll() from object
      • sleep(): until at least time expire or call interrupt
    5. And the last point is use when as estani indicate:

    you normally use sleep() for time-syncronization and wait() for multi-thread-synchronization.

    Please correct me if i'm wrong.

提交回复
热议问题