MultiThreaded Programming  «Prev  Next»

Lesson 5The Runnable interface
Objective Implement the Runnable interface.

Implement Java Runnable Interface

Since Java does not support multiple inheritance, you can not derive from the Thread class if your thread class is already derived from some other class. The solution in this case is to implement the Runnable interface.
Here is the code for an applet that implements the Runnable interface:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class Blink extends Applet implements
 MouseListener, Runnable { 

 Graphics graphics;
 Thread thread;
 Color[] colors = {Color.red, Color.green, Color.blue};
 int index  = 0;
  
 public void init() {
  graphics = getGraphics();
  thread   = new Thread(this);
  thread.start();
  addMouseListener(this);
 }

 public void run() {
  while (true) {
   try {
    graphics.setColor(colors[index]);
    graphics.fillOval(30, 30, 20, 20);
    thread.sleep(500);
    graphics.setColor(Color.white);
    graphics.fillOval(30, 30, 20, 20);
    thread.sleep(250);
   }
   catch (InterruptedException e) {
   }
  }
 }
  
 public void mousePressed(MouseEvent e) {
  index = (index + 1) % colors.length;
 }
 public void mouseClicked(MouseEvent e) {}
 public void mouseEntered(MouseEvent e) {} 
 public void mouseExited(MouseEvent e) {}  
 public void mouseReleased(MouseEvent e) {}  
}

This applet draws a blinking circle that changes color when you press the mouse. There are two threads of execution in this program. The main thread changes the color of the circle when you press the mouse and the helper thread makes the circle blink.

Creating Running Threads - Exercise

Click the Exercise link to create and run a couple of threads.
Create Running Threads - Exercise

Multithreading Fundamentals - Quiz

Test your knowledge of multithreading in this quiz.
Multithreading Fundamentals - Quiz