线程Sleep

方法源码
/**
     * Causes the currently executing thread to sleep (temporarily cease
     * execution) for the specified number of milliseconds, subject to
     * the precision and accuracy of system timers and schedulers. The thread
     * does not lose ownership of any monitors.
     *
     * @param  millis
     *         the length of time to sleep in milliseconds
     *
     * @throws  IllegalArgumentException
     *          if the value of {@code millis} is negative
     *
     * @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.
     */
    public static native void sleep(long millis) throws InterruptedException;
    /**
     * Causes the currently executing thread to sleep (temporarily cease
     * execution) for the specified number of milliseconds plus the specified
     * number of nanoseconds, subject to the precision and accuracy of system
     * timers and schedulers. The thread does not lose ownership of any
     * monitors.
     *
     * @param  millis
     *         the length of time to sleep in milliseconds
     *
     * @param  nanos
     *         {@code 0-999999} additional nanoseconds to sleep
     *
     * @throws  IllegalArgumentException
     *          if the value of {@code millis} is negative, or the value of
     *          {@code nanos} is not in the range {@code 0-999999}
     *
     * @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.
     */
    public static void sleep(long millis, int nanos)

native关键字:Java Native Interface (Java本地接口)

  • sleep(long millis)方法睡眠一定的毫秒数,sleep方法都不回放弃monitor锁,这个非常重要
  • JDK1.5之后引入了一个枚举TimeUnit,对sleep进行了封装,推荐使用此方法来实现sleep。

与sleep类似的是yield方法,也是Thread类提供的一个方法,提醒调用器当前的线程愿意放弃当前获取的CPU资源,如果CPU的资源不紧张的话则此方法相当于失效。若是紧张的话则会提供给其他线程进行使用。yield的方法将线程从RUNNING状态切换到RUNNABLE状态。不过不推荐使用。
sleep和yield的区别:

  • sleep会导致当前线程暂停指定的时间,没有CPU时间片的消耗。
  • yield只是对CPU调度器的一个提示,如果CPU调用器没有忽略这个提示,它会导致线程上下文的切换
  • sleep会使线程短暂block,会在给定的时间内释放CPU资源。
  • yield会使RUNNING状态Thread进入RUNNABLE状态,前提是CPU没有忽略这个提醒。
  • sleep几乎百分百地完成了给定时间的休眠,而yield的提示并不能一定担保。
  • 一个线程sleep另一个线程调用interrupt会捕捉到中断信号,而yield则不会。

Thread.interrupt 中断信号在sleep中会被设置为true,而yield不会产生影响。

原文地址:https://www.cnblogs.com/Mr-GG/p/xian-chengsleep.html