【翻译四】java-并发之线程暂停

时间:2023-03-10 05:57:31
【翻译四】java-并发之线程暂停

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.

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.

The SleepMessages example uses sleep to print messages at four-second intervals:

 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.
« Previous • Trail • Next »
译文:
用Sleep方法暂停正在执行的线程
Thread.sleep方法使正在执行的并发线程挂起一段指定的时间。这对于处理器及时的去处理其他的线程或者应用程序是一个有效的方法。正如同下面的例子,这个sleep方法也能是程序步进,和以后的simplethreads实例一样,对于有时间要求的,可以等待另外一个线程。
这里有两个重载的方法可以使用。一个指定的暂停时间是毫秒,另外一个指定的暂停时间是纳秒。但是,这个暂停时间不一定是精确的,因为它们以来于具体操作系统的设备。正如我们以后课程所见,这个暂停也可能被其他的中断所终止。在任何情况下,这种方法都不保证这个挂起的时间是一个指定的精确的时间。
这个sleepMessages实例,使用sleep方法使打印消息有4秒钟的延迟。
 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]);
}
}
}

主要main函数申明的时候抛出了一个InterruptedException.这个异常是当其他的线程中断了当前活动的sleep方法而抛出的。由于这个应用程序没有定义其他的线程引起这个中断,因此是捕获不到这个异常的。