使用sleep方法暫停一個線程 java
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()方法還能夠用於調整線程執行節奏(見下面的例子)和等待其餘有執行時間需求的線程(這個例子將在下一節演示)。oracle
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.在Thread中有兩個不一樣的sleep()方法,一個使用毫秒錶示休眠的時間,而另外一個使用納秒。因爲操做系統的限制休眠時間並不能保證十分精確。休眠週期能夠被interrupts所中斷,咱們將在後面看到這樣的例子。無論在任何狀況下,咱們都不該該假定調用了sleep()方法就能夠將一個線程暫停一個十分精確的時間週期。app
The
example uses SleepMessages
sleep
to print messages at four-second intervals:ide
SleepMessages程序爲咱們展現了使用sleep()方法每四秒打印一個信息的例子 ui
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()方法就會拋出該異常。因爲這個應用程序並無定義其餘的線程,因此並不用關心如何處理該異常。this