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.lang;

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

public class TimeThread implements Runnable {
    private final 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: 07:18:39.
Now is: 07:18:40.
Now is: 07:18:41.
Now is: 07:18:42.
Now is: 07:18:43.