`sleep()`,`yield()`,`join()`,`wait()`

sleep(),yield(),join(),wait()

sleep()

sleep is a Threadstatic method of the class, so that the current thread within a specified time suspended, but will not release the lock flag

That is the thread into the blocked状态

wait()

The method of the Object class, in the other thread calls notify()/notifyAll()prior to the current thread to keep waiting, will release the lock symbol , other threads can preempt the current thread lock during the wait . Let the thread into the wait (blocked) state

wait and notify function must be used in synchronized or synchronized block of code , although other parts of the compiler can not go wrong, but will throw an exception.

yield()

yield just let the current thread 'give up cpu resources , but to give up time of uncertainty, it is possible to give up after they won the cpu resources. That is, let the thread into the ready state again , yield only make the same priority or higher priority threads get executed 可能yield will not release the lock

join()

Under normal circumstances, often the main thread before the end of the implementation of the other threads. But sometimes the main thread needs to wait for the results of other threads, this time we can use the join()method to make the main thread to suspend execution, perform other thread until another thread is finished, the main thread will then execute.

That is, so that the main thread is blocked, so calling join()thread to execute. Another join(long waitTime), can only make the current thread is blocked wait time milliseconds. When invoked join()when a thread method is interrupted, the program will throw an exception

join(long time)The internal implementation is used wait(long time)to achieve, so in the synchronization code, the lock is released .

Guess you like

Origin www.cnblogs.com/GaryZz/p/11123101.html