Difference between wait() and sleep()

前端 未结 30 3156
無奈伤痛
無奈伤痛 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:27

    Example about sleep doesn’t release lock and wait does

    Here there are two classes :

    1. Main : Contains main method and two threads.
    2. Singleton : This is singleton class with two static methods getInstance() and getInstance(boolean isWait).

      public class Main {
      
      private static Singleton singletonA = null;
      private static Singleton singletonB = null;
      
      public static void main(String[] args) throws InterruptedException {
      
      Thread threadA = new Thread() {
          @Override
          public void run() {
      
              singletonA = Singleton.getInstance(true);
      
          }
      };
      
      Thread threadB = new Thread() {
          @Override
          public void run() {
              singletonB = Singleton.getInstance();
      
              while (singletonA == null) {
                  System.out.println("SingletonA still null");
              }
      
              if (singletonA == singletonB) {
                  System.out.println("Both singleton are same");
              } else {
                  System.out.println("Both singleton are not same");
              }
      
          }
      };
      
      threadA.start();
      threadB.start();
      
       }
      }
      

    and

    public class Singleton {
    
        private static Singleton _instance;
    
        public static Singleton getInstance() {
    
        if (_instance == null) {
            synchronized (Singleton.class) {
                if (_instance == null)
                    _instance = new Singleton();
            }
        }
        return _instance;
    
    }
    
    public static Singleton getInstance(boolean isWait) {
    
        if (_instance == null) {
            synchronized (Singleton.class) {
                if (_instance == null) {
                    if (isWait) {
                        try {
                            // Singleton.class.wait(500);//Using wait
                            Thread.sleep(500);// Using Sleep
                            System.out.println("_instance :"
                                    + String.valueOf(_instance));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
    
                    _instance = new Singleton();
                }
            }
        }
        return _instance;
    
     }
    }
    

    Now run this example you will get below output :

    _instance :null
    Both singleton are same
    

    Here Singleton instances created by threadA and threadB are same. It means threadB is waiting outside until threadA release it’s lock.

    Now change the Singleton.java by commenting Thread.sleep(500); method and uncommenting Singleton.class.wait(500); . Here because of Singleton.class.wait(500); method threadA will release all acquire locks and moves into the “Non Runnable” state, threadB will get change to enter in synchronized block.

    Now run again :

    SingletonA still null
    SingletonA still null
    SingletonA still null
    _instance :com.omt.sleepwait.Singleton@10c042ab
    SingletonA still null
    SingletonA still null
    SingletonA still null
    Both singleton are not same
    

    Here Singleton instances created by threadA and threadB are NOT same because of threadB got change to enter in synchronised block and after 500 milliseconds threadA started from it’s last position and created one more Singleton object.

    0 讨论(0)
  • 2020-11-22 00:29

    Here wait() will be in the waiting state till it notify by another Thread but where as sleep() will be having some time..after that it will automatically transfer to the Ready state...

    0 讨论(0)
  • 2020-11-22 00:30

    sleep is a method of Thread, wait is a method of Object, so wait/notify is a technique of synchronizing shared data in Java (using monitor), but sleep is a simple method of thread to pause itself.

    0 讨论(0)
  • 2020-11-22 00:30

    sleep() is a method which is used to hold the process for few seconds or the time you wanted but in case of wait() method thread goes in waiting state and it won’t come back automatically until we call the notify() or notifyAll().

    The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution, generally.

    Thread.sleep() sends the current thread into the “Not Runnable” state for some amount of time. The thread keeps the monitors it has acquired — i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.

    object.wait() sends the current thread into the “Not Runnable” state, like sleep(), but with a twist. Wait is called on an object, not a thread; we call this object the “lock object.” Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the “wait list” associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.

    synchronized(LOCK) {   
       Thread.sleep(1000); // LOCK is held
    }
    
    synchronized(LOCK) {   
       LOCK.wait(); // LOCK is not held
    }
    

    Let categorize all above points :

    Call on:

    • wait(): Call on an object; current thread must synchronize on the lock object.
    • sleep(): Call on a Thread; always currently executing thread.

    Synchronized:

    • wait(): when synchronized multiple threads access same Object one by one.
    • sleep(): when synchronized multiple threads wait for sleep over of sleeping thread.

    Hold lock:

    • wait(): release the lock for other objects to have chance to execute.
    • sleep(): keep lock for at least t times if timeout specified or somebody interrupt.

    Wake-up condition:

    • wait(): until call notify(), notifyAll() from object
    • sleep(): until at least time expire or call interrupt().

    Usage:

    • sleep(): for time-synchronization and;
    • wait(): for multi-thread-synchronization.

    Ref:diff sleep and wait

    0 讨论(0)
  • 2020-11-22 00:30

    wait and sleep methods are very different:

    • sleep has no way of "waking-up",
    • whereas wait has a way of "waking-up" during the wait period, by another thread calling notify or notifyAll.

    Come to think about it, the names are confusing in that respect; however sleep is a standard name and wait is like the WaitForSingleObject or WaitForMultipleObjects in the Win API.

    0 讨论(0)
  • 2020-11-22 00:32
    • The method wait(1000) causes the current thread to sleep up to one second.
      • A thread could sleep less than 1 second if it receives the notify() or notifyAll() method call.
    • The call to sleep(1000) causes the current thread to sleep for exactly 1 second.
      • Also sleeping thread doesn't hold lock any resource. But waiting thread does.
    0 讨论(0)
提交回复
热议问题