Tuesday, March 17, 2015

Sleep in Java

In order to force waiting with code execution in Java, you can put the thread to sleep for a set amount of time.  Since a process is run by a thread, we can force the thread to suspend execution and wait until the next instruction is interpreted.

In order to do this, we need to find a class that can allow us to pause a thread.  So, you look and see if there a thread class available.  It turns out that there is a Thread class.  So, you look into the class and see what methods it provides, and it turns out that it provides a sleep method.  Actually two sleep methods:


public static void sleep(long millis) throws InterruptedException
public static void sleep(long millis, int nanos) throws InterruptedException

The second method allows you to adjust the sleep time, but in our case we do not need the method to adjust, so you can use the first and simpler method in this project.

So, you need to read the documentation of the method and understand as much about its operation as possible before using it in your own project.  In this case, we find out that it will throw an exception if another thread interrupts the current thread.  We also find out that we need to specify the time it will need to sleep in milliseconds and if we specify a negative number then it will throw an IllegalArgumentException.

Javadoc for sleep method: 
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
Parameters:
millis - the length of time to sleep in milliseconds
Throws:
IllegalArgumentException - if the value of millis is negative
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

So, after you feel comfortable with the method and its capabilities, then you can implement a simple code when you iterate through the code and stop the execution of the code in every iteration by a set amount of time.  I hope, this helps you develop a methodology on how to find a class and a method for projects you'd like to implement.

public class SleepTest {
/**
* Testing of sleep() method from Thread class
* Look at the Java API to find the class and its method documentation in order to understand 
* what exception is thrown and let the calling method handle it by the throws keyword
* http://docs.oracle.com/javase/7/docs/api/

* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
String msgOut[] = {
"Java is cool, ",
"Python is cooler, ",
"but all will not make sense ",
"until you learn C++ !!!"
};

for ( int i = 0 ;  i < msgOut.length ; ) {
//Print a message from the array then go to sleep for 6 seconds
System.out.print(msgOut[i++]);
try{
Thread.sleep(-6000);  //change to a positive value to see it run properly
}
catch(IllegalArgumentException e) {
System.out.println("IllegalArgumentException was caught because "+
                       "you have specified a negative number to sleep for!!!");
System.exit(3);
}
} //end of for loop
} //end of main method
} //end of class


Another example to practice sleep.


/**
 * Write a description of class Wait here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Wait
{
     public static void main(String args[])throws InterruptedException{
    
                 System.out.println("=========== Thank You for Purchasing XYZ Application ==============");
                 for(int y=1500; y>=0;y--){
                      System.out.print("                  ======= Please Wait ===="+y+"====\r");
                      System.out.print("\\\r");
                      Thread.sleep(400);
                      System.out.print("|\r");
                      Thread.sleep(400);
                      System.out.print("/\r");
                      Thread.sleep(400);
                      System.out.print("-\r");
                      Thread.sleep(400);
                      }
          }
}

No comments:

Post a Comment