Difference sleep () and wait () method

1, sleep () statement in the Thread class and a static method;

wait () statement in the Object class, and must be called by the lock object.

2, sleep after () time to reach recovery;

wait () can be set to automatically restore the event, if no time has to be woken up by notfiy;

3, sleep () does not cause the thread to lose lock;

wait () causes the current thread to lose the lock, so that other thread synchronization code block or synchronization method is executed.

 

 

java.lang.Object class way:

(1) wait (): wait

(2) notify () / notifyAll (): wake

They must be called by the "lock / Object Monitor", otherwise it will error.

 

Thread of the life cycle

Point one:

1, New: create a thread object, yet start

2, ready: already started, and can be CPU scheduling

3, run: being scheduled

4, blocking: met: sleep (), wait (), wait (time), the other thread join (), join (time), suspend (), the lock is occupied by other threads, etc.

Back to unblock ready state: sleep () time, notify (), wait time to, the end of the thread stopper, stopper to time, resume (), the other thread holding the lock release the lock.

5, death: run () ends normally encountered an unhandled exception or error, stop ()

Second point:

1, New NEW: create a thread object, yet start

2, run RUNNABLE: CPU can be scheduled, or is scheduled

3, blocked BLOCKED: wait for the lock

4, wait WAITING: wait (), join () and so there is no set time, etc. must notify (), or stoppered end of the thread to resume

5, there is time to wait TIMED_WAITING: sleep (time), wait (time), join (time) and so have time blocking, so time to recover, or interrupt will be restored

6, termination TERMINATED: run () ends normally encountered an unhandled exception or error, stop ()

 

Thread dies, wait () releases the locks

sleep () and yield () does not release the lock

 

Guess you like

Origin www.cnblogs.com/Objecting/p/12233405.html