您的位置:首页 > 编程语言 > Java开发

The Java™ Tutorials — Concurrency :Pausing Execution with Sleep 利用Sleep暂停线程执行

2016-02-11 09:34 585 查看


The Java™ Tutorials — Concurrency :Pausing Execution with Sleep 利用Sleep暂停线程执行

原文地址:https://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html


关键点

sleep的时间不是精确的
当一个线程的休眠被中断时,sleep方法会抛出InterruptedException


全文翻译

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会引起当前线程在一段时间内的阻塞。这个有效手段将会为同一个程序中的其他线程,或者其他程序让出CPU。此方法也可被用于调节节奏,正如下面的例子那样。它还可以用于等待那些持有任务,且需要时间片的其他线程,正如以后课时中SimpleThread样例所示的那样。

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.

Java提供了两个sleep方法的重载版本:它们可以指定具体的休眠时间,不过一个单位是毫秒,一个单位是纳秒。然而,这些休眠时间无法保证是精确的,因为它们受操作系统提供的特性所限制。并且,休眠时间可以由中断所决定,我们将会在下面的章节中看到这点。任何情况下,你不能假定调用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方法就会抛出这个异常。由于这个小程序没有定义能引起中断的其他线程,所有也就无需捕获这个InterruptedException异常了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息