Tuesday, March 27, 2007

Putting a Java pogram to sleep

For a good night's sleep wear comfortable loose clothes, do not consume coffee or tea after 6:00 PM, and read something relaxing before going to bed. Old hat.

ok that's cool, but what if you want to put your Java Thread to sleep? Before Java SE 5, the most common way to put threads to sleep was by calling the sleep() method.


System.out.println("Sleeping for 150 ms");
Thread.sleep(150);
System.out.println("Sleeping for 2 seconds");
Thread.sleep(1000);
System.out.println("Sleeping for 50 nanoseconds");
Thread.sleep(050);
Java2html

 

 

The sleep() method takes a long parameter that  represents the milliseconds we want the thread to sleep. If the time we want our thread to sleep can be easily represented in ms, then this method works out well, but if we want the thread to sleep for some seconds then we have to perform the conversion manually. Even worse, if we want the thread to sleep for nanoseconds, then we have to use the confusing sleep() method that takes 2 parameters as shown in the code above. Such code is not very readable.

Java SE 5 gives us better readability in the form of the TimeUnit class. TimeUnit is an enum that has defines constants for DAYS, HOURS, MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS,  and SECONDS. TimeUnit also has a sleep() method which we can call on the appropriate constant to put the thread to sleep for the number of specified units.


System.out.println("Sleeping for 150 ms");
TimeUnit.MILLISECONDS.sleep(150);
System.out.println("Sleeping for 2 seconds");
TimeUnit.SECONDS.sleep(2);
System.out.println("Sleeping for 50 nanoseconds");
TimeUnit.NANOSECONDS.sleep(50);
Java2html

 

 

Besides this TimeUnit also provides methods for converting values among different time units. Using the TimeUnit enum is definetely preffered over using Thread.sleep() if you are using Java SE 5.

There is one line in the above code samples that I am not sure will work correctly. By "work correctly" I do not mean it will cause a compiler error, but it may not work as promised. Can anyone point out which line?

Discuss this post in the learning forum.



Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

No comments: