How do I create a thread by implementing Runnable interface?

Here is the second way for creating a thread. We create an object that implements the java.lang.Runnable interface. For another example see How do I create a thread by extending Thread class?.

package org.kodejava.example.lang;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class TimeThread implements Runnable {
    private DateFormat df = new SimpleDateFormat("hh:mm:ss");

    // The run() method will be invoked when the thread of this runnable object
    // is started.
    @Override
    public void run() {
        while (true) {
            Calendar calendar = Calendar.getInstance();
            System.out.format("Now is: %s.%n", df.format(calendar.getTime()));

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        TimeThread time = new TimeThread();

        Thread thread = new Thread(time);
        thread.start();
    }
}

An example result of this code are:

Now is: 04:44:59.
Now is: 04:45:00.
Now is: 04:45:01.
Now is: 04:45:02.
Now is: 04:45:03.

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply