How do I use the sleep method of the Thread class?

Here is another example that use the Thread.sleep() method. In the example we create two instances of the ThreadSleepAnotherDemo, we give each thread a name and the sleep interval so that we can see how to thread execution.

package org.kodejava.example.lang;

import java.util.Calendar;

public class ThreadSleep implements Runnable {
    private String threadName;
    private long sleep;

    public ThreadSleep(String threadName, long sleep) {
        this.threadName = threadName;
        this.sleep = sleep;

    // The run() method will be invoked when the thread is started.
    public void run() {
        System.out.println("Start thread [" + this.threadName + "]");
        try {
            while (true) {
                // Pause the thread for "sleep" milliseconds.
                System.out.println("[" + threadName + "]" +
        } catch (InterruptedException e) {
        System.out.println("Finish thread [" + this.threadName + "]");

    public static void main(String[] args) {
        Thread thread1 = new Thread(new ThreadSleep("FirstThread", 1000));
        Thread thread2 = new Thread(new ThreadSleep("SecondThread", 3000));

        // Start the threads

These are the sample output produced by the code snippet above:

Start thread [FirstThread]
Start thread [SecondThread]
[FirstThread]Sun Aug 13 10:42:53 WITA 2017
[FirstThread]Sun Aug 13 10:42:54 WITA 2017
[SecondThread]Sun Aug 13 10:42:55 WITA 2017
[FirstThread]Sun Aug 13 10:42:55 WITA 2017
[FirstThread]Sun Aug 13 10:42:56 WITA 2017

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.