gpt4 book ai didi

Java Thread.sleep() 实现

转载 作者:搜寻专家 更新时间:2023-10-31 08:20:25 26 4
gpt4 key购买 nike

谁能帮我理解 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com