Java Thread.sleep() 实现

标签 java multithreading concurrency thread-sleep

谁能帮我理解 Thread.sleep() 函数是如何实现的?当指定的时间过去或其他线程中断时,线程恢复/唤醒。我有兴趣了解其工作背后的设计模式。

据说 sleep 对 CPU 消耗没有影响。当前线程是否已添加到监听器列表中?何时检查中断标志?调度程序是否持续检查每“x”时间(基于操作系统支持的) hibernate 的每个线程的中断状态?线程如何在不影响 CPU 的情况下取回控制权。

我已经搜索过了。抱歉,如果我遗漏了任何容易找到的链接。

最佳答案

Can someone help me understand how the Thread.sleep() function is implemented?

它在操作系统提供的底层 native 线程上调用sleep

Sleep is said to have no effect on the CPU consumption.

未运行的线程不消耗 CPU 时间。

Is the current thread added to a list of listeners?

没有。

When will the check for interrupt flag occur?

线程无法检查中断标志,因为它没有运行。如果需要,操作系统可以唤醒线程。

Does the scheduler keep checking for the interrupt status of every thread that is sleeping for every "x" amount of time (based on what the OS supports)?

没有。

How does the thread get the control back without effecting the CPU.

线程在时间到期时被操作系统自动唤醒,或者另一个线程可以请求操作系统提前唤醒它。


这是 OpenJVM 中 Thread.sleep() 背后的一些代码:

 2811     ThreadState old_state = thread->osthread()->get_state();
 2812     thread->osthread()->set_state(SLEEPING);
 2813     if (os::sleep(thread, millis, true) == OS_INTRPT) {
 2814       // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
 2815       // us while we were sleeping. We do not overwrite those.
 2816       if (!HAS_PENDING_EXCEPTION) {
 2817         HS_DTRACE_PROBE1(hotspot, thread__sleep__end,1);
 2818         // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
 2819         // to properly restore the thread state.  That's likely wrong.
 2820         THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
 2821       }
 2822     }
 2823     thread->osthread()->set_state(old_state);

关于Java Thread.sleep() 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14026784/

相关文章:

java - 检测关闭的套接字

java - 构建 Eclipse 工作区 OLD 时出错

java - HQL如何查询String的ElementCollection

java - 使用 Spring Boot 从 REST post 请求读取 XML

java - ExecutorService 未经检查的分配

multithreading - JavaFX任务一旦取消就不会重新运行,也不会一次完成

java - AtomicIntegerArray 与 AtomicInteger[]

java - 指定秒内的最大线程调用数

java - 可靠地再现数据库争用

java - 如何在 javafx 中将图像裁剪成碎片,以便用图 block 创建游戏拼图?