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 sleepmethod 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异常了。
相关文章推荐
- C#线程间不能调用剪切板的解决方法
- Lua中实现sleep函数功能的4种方法
- MySQL Sleep连接过多问题解决方法
- C#线程同步的三类情景分析
- C#获取进程或线程相关信息的方法
- C#停止线程的方法
- C#子线程更新UI控件的方法实例总结
- C#线程队列用法实例分析
- nodejs中实现sleep功能实例
- C++使用CriticalSection实现线程同步实例
- 基于C++实现的线程休眠代码
- 探究在C++程序并发时保护共享数据的问题
- VB读取线程、句柄及写入内存的API代码实例
- C#网络编程基础之进程和线程详解
- C#通过Semaphore类控制线程队列的方法
- C#多线程处理多个队列数据的方法
- C#实现线程安全的简易日志记录方法
- C#中线程同步对象的方法分析
- Nodejs实战心得之eventproxy模块控制并发
- ASP.NET线程相关配置