Suspending a Thread through sleep()


Threads can be suspended using the static sleep() method.

The sleep() method is defined in the Thread class and has two overloads:

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

The sleep() will suspend the thread execution until the specified period.

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

Let's look at an example that will print us date in terms of seconds since 1970.

import java.util.Date;
public class MrSleep {

    public static void main(String[] args) {
        for(;;)
        {
            //the number of seconds since January 1, 1970, 00:00:00 GMT 
            long seconds=new Date().getTime()/1000;
            System.out.println("Seconds: "+seconds);
            //suspend thread for a second
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Result

Seconds: 1523713737
Seconds: 1523713738
Seconds: 1523713739
Seconds: 1523713740
Seconds: 1523713741
Seconds: 1523713742
Seconds: 1523713743
Seconds: 1523713744
......

We suspend the thread for a second and print the date. We've converted the date to seconds. The date is counted since January 1, 1970, 00:00:00 GMT.

This program can theoretically run infinitely, forever upto the end of time.

Best Regards.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post