让我说我有一个线程T并且它持有一个资源R.如果我在当前线程上调用Thread.sleep()即T,它会释放资源R(让其他线程使用它) )睡觉前或不睡觉? 或者它将保留该资源,并且当它将唤醒时它将使用资源R并且在完成工作后它将释放它吗?
答案 0 :(得分:8)
Thread.sleep()方法在给定的时间段内有效地“暂停”当前线程。我们在第一个threading example中使用它来使线程定期显示消息,在消息之间休眠。从一开始,重要的是要注意以下事项:
它始终是当前线程进入睡眠状态;
主题可能无法停留所需的时间(甚至根本没有);
睡眠持续时间将受某些系统特定的影响 粒度,通常为1毫秒;
在休眠时,线程仍拥有同步锁 获取的;
睡眠可以被打断(有时用于实现睡眠 取消功能);用某些值调用sleep()可以有 对OS的一些微妙的全局影响(见下文),反之亦然, 系统上运行的其他线程和进程可能会有细微之处 对观察到的睡眠持续时间的影响。
答案 1 :(得分:6)
首先,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。它' S 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.
希望它会有所帮助! 干杯...
答案 2 :(得分:2)
正在睡眠的线程将在睡眠时保持锁定(not release resource)
。一个睡眠的线程甚至不会被安排在它睡觉的时间(或直到它被中断然后它被唤醒)
答案 3 :(得分:1)
如果您的资源R是java监视器,那么只有两种方法可以释放它:
synchronized
阻止wait
答案 4 :(得分:1)
Javadoc 表示 - sleep()
:导致当前正在执行的线程休眠(暂时停止执行)指定的毫秒数,具体取决于系统计时器的精度和准确性和调度程序
Thread.sleep()方法本质上与线程调度程序交互,以将当前线程置于所需间隔的等待状态。但是,该线程不会失去任何监视器的所有权。
为了允许中断,实现可能实际上不使用大多数操作系统提供的显式睡眠功能。
如果当前线程在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。