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
Step 3 - Testing
OutputWhat 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>> |