"Hello, Amigo! Today Bilaabo will tell you about the most interesting method we use when working with threads: sleep. The sleep method is declared as a static method of the Thread class, i.e. it is not attached to any object. The purpose of this method is to make the program «fall asleep» for a while. Here's how it works:"

Code Description
public static void main(String[] args)
{
Thread.sleep(2000);
}

The program starts.

Then it freezes for 2 seconds (2,000 milliseconds)

Then it ends.

The sleep method's only parameter is a length of time. The time interval is specified in thousandths of a second (milliseconds). Once a thread calls this method, it falls asleep for the specified number of milliseconds.

"When is it best to use this method?"

"This method is often used in child threads when you need to do something regularly but not too often. Look at this example:"

Code Description
public static void main(String[] args)
{
while (true)
{
Thread.sleep(500);
System.out.println("Tick");
}
}
The program will run forever. The loop condition is always true.

Here's what the program does in the loop:
a) sleep for half a second
b) display «Tick» on the screen

That is, some action will be performed twice a second.

"Ooh, now that's interesting."

"Glad you like it, my friend!"

"What if I want to perform an action 100 times a second. What should I do?"

"If an action should be executed 100 times per second and there are 1000 milliseconds in a second, then the action needs to be performed once every 10 milliseconds."

If your action takes 2 milliseconds, then you should add an 8-millisecond delay. Taken together, they will be executed every 10 milliseconds. And that works out to 100 times per second.

If your action is almost instantaneous, add a 10-millisecond delay (sleep). Then it will be executed about 100 times per second.

"Thank you, Bilaabo."