Thead对象的sleep方法,和yield方法有何区别,为什么实现的线程中,在run方法中要调用sleep方法?

?

看来这里的高手们都觉得太简单了,不屑回答,我帮你把Thread源文件里的这两个方法的内容帖出来,看看就明白了

/**
* 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 <i>interrupted status</i> of the
* current thread is cleared when this exception is thrown.
* @see java.lang.Objectnotify()
*/
> 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 <i>interrupted status</i> of the
* current thread is cleared when this exception is thrown.
* @see java.lang.Objectnotify()
*/
> 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);
> }


从操作系统的角度讲,os会维护一个ready queue(就绪的线程队列)。并且在某一时刻cpu只为ready queue中位于队列头部的线程服务。

但是当前正在被服务的线程可能觉得cpu的服务质量不够好,于是提前退出,这就是yield。

或者当前正在被服务的线程需要睡一会,醒来后继续被服务,这就是sleep。

sleep方法不推荐使用,可用wait。

线程退出最好自己实现,在运行状态中一直检验一个状态,如果这个状态为真,就一直运行,如果外界更改了这个状态变量,那么线程就停止运行。