/
* Causes the currently executing thread object to temporarily pause
* and allow other threads to execute.
*/
> public static native void yield();
/
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified number of milliseconds. The thread
* does not lose ownership of any monitors.
*
* @param millis the length of time to sleep in milliseconds.
* @exception InterruptedException if another thread has interrupted
* the current thread. The interrupted status of the
* current thread is cleared when this exception is thrown.
* @see java.lang.Object#notify()
*/
> public static native void sleep(long millis) throws InterruptedException;
/**
* Causes the currently executing thread to sleep (cease execution)
* for the specified number of milliseconds plus the specified number
* of nanoseconds. The thread does not lose ownership of any monitors.
*
* @param millis the length of time to sleep in milliseconds.
* @param nanos 0-999999 additional nanoseconds to sleep.
* @exception IllegalArgumentException if the value of millis is
* negative or the value of nanos is not in the range
* 0-999999.
* @exception InterruptedException if another thread has interrupted
* the current thread. The interrupted status of the
* current thread is cleared when this exception is thrown.
* @see java.lang.Object#notify()
*/
> public static void sleep(long millis, int nanos)
throws InterruptedException {
> if (millis < 0) {
> throw new IllegalArgumentException("timeout value is negative");
> }
>
> if (nanos < 0 || nanos > 999999) {
> throw new IllegalArgumentException(
"nanosecond timeout value out of range");
> }
>
> if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
> millis++;
> }
>
> sleep(millis);
> }
但是当前正在被服务的线程可能觉得cpu的服务质量不够好,于是提前退出,这就是yield。
或者当前正在被服务的线程需要睡一会,醒来后继续被服务,这就是sleep。
线程退出最好自己实现,在运行状态中一直检验一个状态,如果这个状态为真,就一直运行,如果外界更改了这个状态变量,那么线程就停止运行。