CodeGym /Courses /Java Core /Healthy sleep

Healthy sleep

Java Core
Level 6 , Lesson 6
Available

"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."

Comments (6)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
23 July 2023
This is cool
Hoist Level 3, San Diego, United States
13 November 2022
This has been good to go thru to get a better understanding the JavaScript call stack too --- improving my multi-code language skills for sure. Programming is way more fun now after APEX Salesforce - C# - C++ Unreal Engines.
Karas Level 20, Tampa, United States
17 September 2021
I had no idea how this is usefull but then when is added to multithreading and also taking the speed of the computers... then you see why it is needed.
TheLordJackMC Level 39, Princeton, idk somewhere
17 July 2021
why does he speak in the 3rd person?
Muhammad Vahhaaj Level 19, Rawalpindi, Pakistan
15 July 2019
So we are basically reducing the processing on purpose.
Clint Level 22, cincinnati, united states
3 December 2020
you can also think of it as "pausing" for however long you want. Tends to work the same in most languages