An Example
Home ] Up ] Creating a Thread ] Stopping a Thread ] Extending the Thread Class ] Implementing Runnable ] [ An Example ]

 

 

Here is an example of an applet that uses the Runnable interface technique: a clock applet.

Your browser apparently doesn't support Java! Please enable it.

Here's the source for this applet. Note how the applet's stop()method (not to be confused with the thread's stop() method!) causes the thread to stop, by setting the m_clockThread field to null, thus causing the thread's run loop to terminate.

package threads;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.util.Calendar;
import java.util.Date;
import java.text.DateFormat;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class ClockApplet extends JApplet implements Runnable
{
  /**
   * The applet init method.
   * Initializes the GUI
   */
  @Override
  public void init()
  {
    EventQueue.invokeLater( new Runnable()
      {
        public void run()
        {
          m_timeLabel = new JLabel("The Time is...", SwingConstants.CENTER);
          m_timeLabel.setFont( new Font("Dialog", Font.BOLD, 16) );
          add(m_timeLabel);
        }
      }
    );
  }
  
  /**
   * The applet start method.
   * Starts up the thread to keep the clock updated.
   */
  @Override
  public void start()
  {
    if (m_clockThread == null)
    {
      m_clockThread = new Thread(this, "Clock");
      m_clockThread.start();
    }
  }
  
  /**
   * The Runnable run method.
   * Keeps the clock updated every second.
   */
  public void run()
  {
    // Loop until m_clockThread is set to null
    while (m_clockThread != null)
    {
      try
      {
        Thread.sleep(1000); // For 1 second
        // Change the label to the current time
        EventQueue.invokeLater( new Runnable()
          {
            // Update the label in the event handling thread.
            public void run()
            {
              Calendar cal = Calendar.getInstance();
              Date date = cal.getTime();
              DateFormat dateFormatter = DateFormat.getTimeInstance();
              m_timeLabel.setText(dateFormatter.format(date));
            }
          }
        );
      }
      catch (InterruptedException e)
      {
        // Ignore
      }
    }
  }
  
  /**
   * The applet stop method
   */
  @Override
  public void stop()
  {
    m_clockThread = null;
    super.stop();
  }
  
  /////// Private data ///////////
  private Thread m_clockThread = null;
  private JLabel m_timeLabel;
}
 
The page was last updated February 19, 2008