The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Essential Java Classes
Lesson: Threads: Doing Two or More Tasks at Once

Implementing the Runnable Interface

The Clock applet displays the current time and updates its display every second. You can scroll the page and perform other tasks while the clock updates. The reason is that the code that updates the clock's display runs within its own thread.


Note: If you don't see the applet running above, you need to install Java Plug-in, which happens automatically when you install the J2SE JRE or JDK. This applet requires JDK 5.0 or later. You can find more information in the Java Plug-in home page.

The Clock applet uses a technique different from SimpleThread's for providing the run method for its thread. Instead of subclassing Thread, Clock implements the Runnable interface and therefore implements the run method defined in it. Clock then creates a thread with itself as the Thread's target. When created in this way, the Thread gets its run method from its target. The code that accomplishes this is shown in boldface in the following.

import java.awt.*;
import java.util.*;
import java.applet.*;
import java.text.*;

public class Clock extends java.applet.Applet
                   implements Runnable {
    private volatile Thread clockThread = null;
    DateFormat formatter;     //Formats the date displayed
    String lastdate;          //String to hold date displayed
    Date currentDate;         //Used to get date to display
    Color numberColor;        //Color of numbers
    Font clockFaceFont;
    Locale locale;

    public void init() {
        setBackground(Color.white);
        numberColor = Color.red;
        locale = Locale.getDefault();
        formatter =
            DateFormat.getDateTimeInstance(DateFormat.FULL,
            DateFormat.MEDIUM, locale);
        currentDate = new Date();
        lastdate = formatter.format(currentDate);
        clockFaceFont = new Font("Sans-Serif",
                                 Font.PLAIN, 14);
        resize(275, 25); 
    }

    public void start() {
      if (clockThread == null) {
         clockThread = new Thread(this, "Clock");
         clockThread.start();
      }
    }

    public void run() {
      Thread myThread = Thread.currentThread();
        while (clockThread == myThread) {
            repaint();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e){ }
        }
    }

    public void paint(Graphics g) {
      String today;
      currentDate = new Date();
      formatter =
           DateFormat.getDateTimeInstance(DateFormat.FULL,
           DateFormat.MEDIUM, locale);
      today = formatter.format(currentDate);
      g.setFont(clockFaceFont);

      //Erase and redraw  
      g.setColor(getBackground());
      g.drawString(lastdate, 0, 12);   				

      g.setColor(numberColor);
      g.drawString(today, 0, 12);    
      lastdate = today;
      currentDate = null;
    }

    public void stop() {
        clockThread = null;
    }
}
The Clock applet's run method loops until the browser asks it to stop. During each iteration of the loop, the clock repaints its display. The paint method figures out what time it is, formats it in a localized way, and displays it. You'll see more of the Clock applet in the The Life Cycle of a Thread (in the Essential Java Classes trail) section, which uses it to teach you about the life of a thread.

Deciding to Use the Runnable Interface

You have now seen two ways to provide the run method: There are good reasons for choosing one of these options over the other. However, for most cases, including that of the Clock applet, if your class must subclass some other class (the most common example being Applet), you should use Runnable.

To run in a browser, the Clock class has to be a subclass of the Applet class. Also, the Clock applet needs a thread so that it can continuously update its display without taking over the process in which it is running. (Some browsers might create a new thread for each applet so as to prevent a misbehaved applet from taking over the main browser thread. However, you should not count on this when writing your applets; your applets should create their own threads when doing computer-intensive work.) But because the Java programming language does not support multiple-class inheritance, the Clock class cannot be a subclass of both Thread and Applet. Thus, to provide its threaded behavior, the Clock class must use the Runnable interface.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.