JUC 源码讲解:sleep()

JUC 源码讲解:sleep()

抛出问题

sleep() 能使线程进入 TIMED_WAITING 状态,那么,在使用sleep()会不会释放锁?被中断了会不会抛出异常?在线程使用sleep()时,CPU会不会被释放?我们在源码中和实战中看看答案吧!

查看源码

进入 sleep() 源码,可以看到它是一个 native 方法,但是注释很详细,让我们拆开分析一下:

    /**
     * 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;

我们看到,这个 sleep() 方法抛出了一个异常,说明是对中断敏感的

那么,会不会释放锁资源呢?

在第一段中有这样一句话

The thread does not lose ownership of any monitors.

线程不会失去任何锁!

那么,在使用 sleep() 时,CPU会不会被释放呢?我们在文档里找不到答案,就自己模拟试一下吧!

可以 start 100个Thread线程,让他们都进入 sleep() 状态,因为有100个线程,普通的家用CPU一定会爆掉,这时候,我们在任务管理器中观察CPU使用率发现,CPU的使用率并没有显著的变化!因此,在sleep()的时候,线程会释放掉CPU资源!,感兴趣的小伙伴可以手动模拟试一下


模拟思路(可以跳过)

这段代码 sleep() 100个线程

{

    public static void main(String[] args) {

        for (int i = 0; i < 100; i++) {
            new Thread(new MyThread(), "YY-Thread-"+i).start();
        }
    }

    static class MyThread implements Runnable {

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(500000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                System.out.println("FUNLLY!");
            }
        }
    }
}

观察到 CPU 资源占用仍然很低

在 stack log 中找到我们创建的线程,观察其为 TIMED_WAITING 状态

总结

  • sleep 不会释放任何锁

  • sleep 是对中断敏感的

  • sleep 时会释放CPU资源

posted @ 2024-03-13 19:20  yangruomao  阅读(7)  评论(0编辑  收藏  举报