Thursday, April 23, 2009

201 very sleepy

You can put your program to sleep like this:

  try { Thread.currentThread().sleep(millis); }
  catch (InterruptedException e) 
     { System.out.println("Error sleeping"); }

This code is seen in StdDraw.

Why put the program to sleep? For animation: otherwise, it might move too fast. If you have a sequence of instructions, possibly in a loop, that you want to execute more slowly so you can admire your work at a humane pace, put a few milliseconds of sleep-time between them.

Both the Thread object and the InterruptedException object are in java.lang, so you don't have to import them. We will talk about exceptions next week.

No comments: