J2EEOnline J2EE  






MultiThreaded Programming  «Prev  Next»
Lesson 5The Runnable interface
Objective Implement the 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:


  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.
Creating Running Threads - Exercise
Multithreading Fundamentals - Quiz
Test your knowledge of multithreading in this quiz.
Multithreading Fundamentals - Quiz