【翻译四】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:

 1 public class SleepMessages {

 2     public static void main(String args[])

 3         throws InterruptedException {

 4         String importantInfo[] = {

 5             "Mares eat oats",

 6             "Does eat oats",

 7             "Little lambs eat ivy",

 8             "A kid will eat ivy too"

 9         };

10 

11         for (int i = 0;

12              i < importantInfo.length;

13              i++) {

14             //Pause for 4 seconds

15             Thread.sleep(4000);

16             //Print a message

17             System.out.println(importantInfo[i]);

18         }

19     }

20 }
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.

你可能感兴趣的:(java)