繁体   English   中英

Java Thread.sleep()实现

[英]Java Thread.sleep() implementation

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

据说睡眠对CPU消耗没有影响。 当前线程是否已添加到侦听器列表中? 什么时候会检查中断标志? 调度程序是否继续检查每个“x”时间内正在休眠的每个线程的中断状态(基于操作系统支持的内容)? 线程如何在不影响CPU的情况下获得控制权。

我搜索过这个。 对不起,如果我错过了任何容易找到的链接。

有人可以帮我理解Thread.sleep()函数是如何实现的吗?

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

据说睡眠对CPU消耗没有影响。

未运行的线程不占用CPU时间。

当前线程是否已添加到侦听器列表中?

没有。

什么时候会检查中断标志?

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

调度程序是否继续检查每个“x”时间内正在休眠的每个线程的中断状态(基于操作系统支持的内容)?

没有。

线程如何在不影响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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM