Home‎ > ‎Applied Core Java‎ > ‎Threads‎ > ‎

Sleep Method

Problem : How you will create a thread that will periodically wake-up and perform certain tasks?

Solution : Thread class has sleep() method that sleeps a thread for given milliseconds before executing next task.

Program :

Step 1 - Coding

Create a text file c:\sunilos\SleepMessages.java  and copy below contents.


 * A program using Thread.sleep method

public class SleepMessages {
    public static void main(String args[]) throws InterruptedException {
        String importantInfo[] = {
                "What is Monitor?",

                "Is it computer hardware ?",
                "What do you think?",

                "No, it is monitor key used to synchronize methods in threads",
                "Wonderful!! You are intelligent"

        for (int i = 0; i < importantInfo.length; i++) {

            //Dude ! take a nap for 4 seconds
            Thread.sleep(4000); // 4000 in milliseconds

            // Print a message

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy SleepMessages.java into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile SleepMessages.java with help of 
    • javac SleepMessages.java command.  Compiled class file will be created in the same folder
  5. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your  java program from command prompt with help of 
    • java SleepMessages  command.


What is Monitor?
Is it computer hardware ?
What do you think?
No, it is monitor key used to synchronize methods in threads
Wonderful!! You are intelligent

<<Previous | Next>>
Namrata Sisodiya,
Aug 19, 2011, 11:40 PM