Thread.sleep()如何在内部工作 [英] How Thread.sleep() works internally

查看:118
本文介绍了Thread.sleep()如何在内部工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个线程T,它持有一个资源R.如果我在当前线程上调用Thread.sleep()(即T),它会释放资源R(让其他线程使用它)睡眠与否?
或者它会保存该资源,当它将被唤醒时将使用资源R,完成工作后它会释放它吗?

解决方案

此Javamex文章


Thread.sleep ()方法在给定时间段内有效地暂停当前线程。我们在第一个线程示例中使用它,使线程定期显示消息,睡眠消息之间。从一开始,请务必注意以下事项:




  • 始终是当前线程可以睡眠;


  • 线程可能不会睡眠所需时间p>


  • 睡眠时间将受某些系统特定的
    粒度的限制,通常为1ms;


  • 在睡觉时,线程仍拥有同步锁,它已获取
    ;


  • 睡眠可以中断(有时对于实现
    取消函数很有用);调用sleep()某些值可以有
    一些微妙的全局效应操作系统(见下文),反之亦然,
    系统上运行的其他线程和进程可以有微妙的
    效果对所观察的睡眠持续时间。




Let's say I have a thread T and it is holding one resource R. If I call Thread.sleep() on the current thread i.e T, will it release the resource R (to let other threads use it) before going to sleep or not? Or it will hold that resource and again when it will awake it will use the resource R and after finishing the work will it release it?

解决方案

From this Javamex article:

The Thread.sleep() method effectively "pauses" the current thread for a given period of time. We used it in our very first threading example to make threads display a message periodically, sleeping between messages. From the outset, it's important to be aware of the following:

  • it is always the current thread that is put to sleep;

  • the thread might not sleep for the required time (or even at all);

  • the sleep duration will be subject to some system-specific granularity, typically 1ms;

  • while sleeping, the thread still owns synchronization locks it has acquired;

  • the sleep can be interrupted (sometimes useful for implementing a cancellation function); calling sleep() with certain values can have some subtle, global effects on the OS (see below), and vice versa, other threads and processes running on the system can have subtle effects on the observed sleep duration.

这篇关于Thread.sleep()如何在内部工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆