The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
Thread.sleep
causes the current thread to suspend execution for a specified period. 导致当前线程在指定的时间段内暂停执行。This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. 这是一种使处理器时间可用于应用程序的其他线程或可能在计算机系统上运行的其他应用程序的有效方法。The sleep
method can also be used for pacing, as shown in the example that follows, and waiting for another thread with duties that are understood to have time requirements, as with the SimpleThreads
example in a later section.sleep
方法还可以用于调整步调(如下面的示例所示),以及等待另一个具有任务的线程,该任务被理解为具有时间要求,如后面一节中的SimpleThreads示例所示。
Two overloaded versions of 提供了两种重载版本的sleep
are provided: one that specifies the sleep time to the millisecond and one that specifies the sleep time to the nanosecond. sleep
:一种将睡眠时间指定为毫秒,另一种将睡眠时间指定为纳秒。However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS. 但是,这些睡眠时间不能保证精确,因为它们受到底层操作系统提供的功能的限制。Also, the sleep period can be terminated by interrupts, as we'll see in a later section. 此外,睡眠时间可以通过中断来终止,我们将在后面的部分中看到。In any case, you cannot assume that invoking 在任何情况下,您都不能假设调用sleep
will suspend the thread for precisely the time period specified.sleep
将在指定的时间段内暂停线程。
The
example uses SleepMessages
sleep
to print messages at four-second intervals:
示例使用SleepMessages
sleep
以四秒钟的间隔打印消息:
public class SleepMessages { public static void main(String args[]) throws InterruptedException { String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" }; for (int i = 0; i < importantInfo.length; i++) { //Pause for 4 seconds Thread.sleep(4000); //Print a message System.out.println(importantInfo[i]); } } }
Notice that 注意,main
declares that it throws InterruptedException
. main
声明它throws InterruptedException
。This is an exception that 这是当另一个线程在sleep
throws when another thread interrupts the current thread while sleep
is active. sleep
处于活动状态时中断当前线程时,sleep
引发的异常。Since this application has not defined another thread to cause the interrupt, it doesn't bother to catch 由于此应用程序尚未定义另一个线程来引起中断,因此它不需要捕获InterruptedException
.InterruptedException
。