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

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异常了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值