Thread.sleep()如何在内部工作

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

从这篇Javamex文章 :

Thread.sleep()方法在给定的时间段内有效地“暂停”当前线程。 我们在第一个线程示例中使用它来使线程定期显示消息,在消息之间hibernate。 从一开始,重要的是要注意以下事项:

  • 它始终是当前正在进入睡眠状态的线程;

  • 线程可能无法在所需时间内睡眠 (甚至根本不睡觉 );

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

  • 在睡觉时,线程仍然拥有它已经获得的同步锁 ;

  • 睡眠可以中断(有时用于实现取消function); 使用某些值调用sleep()可能会对操作系统产生一些微妙的全局影响(见下文),反之亦然,系统上运行的其他线程和进程可能会对观察到的睡眠持续时间产生微妙的影响。

首先,Thread.sleep()是阻塞库方法。 线程可能会阻塞或暂停,原因如下:等待I / O完成,等待获取锁定,等待从Thread.sleep唤醒,或等待另一个线程中的计算结果。 当线程阻塞时,它通常被挂起并置于其中一个被阻塞的线程状态中。

So, when you call the sleep() method, Thread leaves the CPU and stops its execution for a period of time. During this time, it's not consuming CPU time, so the CPU can be executing other tasks.When Thread is sleeping and is interrupted, the method throws an InterruptedException exception immediately and doesn't wait until the sleeping time finishes. 

Java并发API有另一种方法使Thread对象离开CPU。 它是yield()方法,它向JVM指示Thread对象可以离开CPU执行其他任务。 JVM不保证它将遵守此请求。 通常,它仅用于调试目的。

与sleep()混淆的一个问题是它与对象类的wait()方法有何不同

 The major difference between wait and sleep is that wait() method release the acquired monitor when thread is waiting while Thread.sleep() method keeps the lock or monitor even if thread is waiting. 

希望它会有所帮助! 干杯…

正在睡眠的线程将在睡眠时保持锁定(not release resource) 。 一个睡眠的线程甚至不会被安排在它睡觉的时间(或直到它被中断然后它被唤醒)

如果您的资源R是java监视器,那么只有两种方法可以释放它:

  • 退出synchronized
  • 呼叫wait监视器

Javadoc说 – sleep()使当前正在执行的线程hibernate(暂时停止执行)指定的毫秒数,这取决于系统定时器和调度程序的精度和准确性

Thread.sleep()方法基本上与线程调度程序交互,以将当前线程置于所需间隔的等待状态。 但是线程不会失去任何监视器的所有权。

为了允许中断,实现可能实际上不使用大多数OS提供的显式睡眠function。

如果在调用wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int)wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int)阻塞当前线程wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int)methods of Thread class ,然后它的中断状态将被清除,它将收到InterruptedException。