Suspending a Thread through sleep()

| Page Views: 48

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) {
            //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 {
            } catch (InterruptedException e) {


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.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.


What do You Think

Previous Post Next Post