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 ThreadSleepAnotherDemo implements Runnable {
    private String threadName;
    private long sleep;

    public ThreadSleepAnotherDemo(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.
                //
                Thread.sleep(this.sleep);
                System.out.println("[" + threadName + "]" +
                        Calendar.getInstance().getTime());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(
                "Finish thread [" + this.threadName + "]");
    }

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

        //
        // Start the threads
        //
        thread1.start();
        thread2.start();
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply