Documentation

The Java™ Tutorials
Hide TOC
Pausing Execution with Sleep用睡眠暂停执行
Trail: Essential Java Classes
Lesson: Concurrency
Section: Thread Objects

Pausing Execution with Sleep用睡眠暂停执行

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 SleepMessages example uses 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 InterruptedExceptionThis 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


Previous page: Defining and Starting a Thread
Next page: Interrupts