Implementing the Runnable Interface

The Runnable interface consists of a single method run() which required for implementing thread. We will create a thread and pass the object of the class that implements the Runnable interface as an argument of the Thread class’s constructor. The thread will now be activated by calling the start().

 

Example...

import java.awt.Graphics;

import java.awt.Color;

 import java.awt.Font;

import java.applet.*;

 

 

public class ColorSwirl extends Applet implements Runnable {

Font f = new Font("Arial",Font.BOLD/Font.ITALIC,51);

     Color colors[] = new Color[50];

   Thread runnThread;

   public void start() {

       if (runnThread == null) {

           runnThread = new Thread(this);

           runnThread.start();

       }

   }

   public void stop() {

       if (runnThread != null) {

           runnThread.stop();

           runnThread = null;

       }

   }

   public void run() {

       // initialize the color array

       float c = 0;

       for (int i = 0; i < colors.length; i++) {

           colors[i] =

           Color.getHSBColor(c, (float)1.0,(float)1.0);

           c += .02;

       }

       // cycle through the colors

       int i = 0;

       while (true) {

           setForeground(colors[i]);

           repaint();

           i++;

          try { Thread.sleep(50); }

           catch (InterruptedException e) { }

           if (i == colors.length ) i = 0;

       }

   }

   public void paint(Graphics grraph) {

       grraph.setFont(f);

       grraph.drawString("XCnotes.com", 15, 50);

     grraph.drawLine(10,100,500,100);

       grraph.drawLine(10,110,500,110);

   }

}

//<applet code="ColorSwirl.class" height=500 width=500></applet>

Runnable Interface in Java

About Us

Rekha SetiaRekha Setia is a passionate blogger of Extra Computer Notes. if you have any ideas or any request me @