The difference between sleep and the Java wait

A difference

  1. Thread class from sleep, and wait from the Object class
  2. The method of sleep does not release the lock, the lock release wait method, so that the control block or other thread synchronization method may be used
  3. wait, notify, and notifyAll only synchronous or a synchronous control method for use inside the control block, and can be used anywhere sleep
  4. sleep must catch the exception, and wait, notify and notifyAll do not need to catch the exception

Second, the concept

sleep: After sleep method belongs to the Thread class method, so that represents a thread to sleep, waiting for a certain time, automatically wakes up into an operational state, it will not begin to run, because the thread scheduling mechanism also needs to restore the threads running time after that, a thread object method called sleep, and he does not release all held some object lock, and therefore would not affect the operation of other processes objects. But in the process of sleep in the process may be called its interrupt other objects (), resulting in abnormal InterruptedException, if your program does not catch this exception, the thread will be terminated abnormally into the TERMINATED state, if your program captures this the exception, then the program will continue to execute the catch block (possibly finally block) and later code.

wait: Wait belonging to members of the Object methods, once an object called the wait method, you must be using notify () and notifyAll () method wakes up the process; if the thread has a lock synchronization or some object, then call the wait ( after), this thread will release all synchronous resources it holds, but not limited to the object that is called the wait () method. wait () method will also likely during the wait to be called interrupt () method to generate other objects.

Guess you like

Origin www.cnblogs.com/lsys/p/11249761.html