How to Program Pauses in Java

There are several ways to stop an application thread in Java, but the best way is by using the "thread.sleep()" method. Other methods such as "wait()" and "SocketinputStream.read()" can be used, but in the big picture of the application, they just add more complications than necessary. There is no reason to implement "runnable" when executing "sleep." If a "thread.interrupt" awakens the thread, then the "interruptedException" will become active.

Instructions

    • 1

      Find the area of code where you want to create the pause.

    • 2

      Place the following lines of code into the thread:

      try{

      Thread.sleep(x);

      }

      Catch(InterruptedException e ) {

      System.out.println("Thread Interrupted")

      }

      The sleep parameter (x) is measured in milliseconds. If you place the value 1000 here then the thread will pause for 1 second.

    • 3

      Run the code to verify the pause duration. The pause may be a little longer because of the operating system. The more CPU resources that are being used, the longer the pause duration will be. If you run the code several times, you will notice a small deviation in the pause.

Related Searches:

References

Resources

Comments

You May Also Like

Related Ads

Featured