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?",

                "Hum...",
                "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
            System.out.println(importantInfo[i]);
        }
    }
}

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.

Output

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



<<Previous | Next>>
ċ
SleepMessages.java
(1k)
Mahima Hardia,
Aug 19, 2011, 11:40 PM
Comments