Applet Thread Example

In this tutorial, we show you on how to display system time using thread method in java language.
Requirements:
  • JDK - Java Development Kit
  • Any Java Editor (Jcreator, NetBeans, Eclipse...)
Screenshot


Code snippet:

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

public class ThreadExample extends Applet implements Runnable
{
      Thread clockThread;
      TextField clockField;
      Date date;
      boolean running = true;
      public void init()
      {
            setLayout(new BorderLayout());
            clockField = new TextField();
            add(clockField,"Center");
            clockThread= new Thread(this);
            clockThread.start();
      }

      public void destroy()
      {
            running = false;
            clockThread = null;
      }

      public void run()
      {
            while (running)
            {
                  date = new Date();
                  String time = date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();

                  clockField.setText(time);

                  try
                  {
                        clockThread.sleep(500);
                  }
                  catch (InterruptedException e)
                  {
                        System.out.println(e);
                  }
            }
      }
}