Pausing Execution with Sleep

Pausing Execution with Sleep
用睡眠(Sleep)暂停执行(Execution)
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.
Thread.sleep能够使当前线程在一个指定的时段暂停执行。这是一种为应用程序的其他线程或电脑系统中其他应用程序提供处理器时间的有效方法。这个sleep方法也用于
调步(pacing),如同下面的例子。并且等待另外一个被认为有时间需求任务的线程,如同下一章的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. 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方法有2个重载的版本可以提供:一种指定的暂停时间是微秒级的,一种指定的睡眠时间是纳秒级别的。然而这些暂停时间不保证会精确,因为它们受底层操作系统提供的工具的限制。而且暂停期间可以被中断(interrupts)终止,就像我们在下课看到的那样。在任何情况下,你不能够假设调用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. This is an exception that sleep throws when another thread interrupts the current thread while sleep is active. Since this application has not defined another thread to cause the interrupt, it doesn't bother to catch InterruptedException.
注意main方法申明了它会抛出InterruptedException异常。当sleep是活动的,其他线程中断了当前线程sleep会抛出这个异常。因为这个应用程序没有定义其他的线程造成中断,它不用担心捕获这个异常

posted @ 2012-05-20 21:22  yuwenxing  阅读(161)  评论(0编辑  收藏  举报