All ITKnowledge Source Code Search Tips Advanced Search |

| Mastering Java Threads by Marc Adler and David Herst DDC Publishing, Inc. ISBN: 1562438425 Pub Date: 05/01/99

Search this book:

Previous | Table of Contents | Next

## Chapter 3
The Runnable Interface

Lesson Topics

  • The Runnable Interface

### The Runnable Interface

The Java declaration of the Runnable interface is as follows:

    public interface Runnable extends Object

#### Java Interface Defined

As you already learned, an interface in Java is an abstraction of a class (such as an abstract class in C++). If your class implements an interface, you are responsible for implementing the methods that the interface defines. In the case of the Runnable interface, you are responsible for implementing the only method within Runnable—the run() method.

A Java Object should implement the Runnable interface if it is intended to execute code. If a Java Object implements Runnable, the Java Virtual Machine (VM) will eventually call the run() function, which that object implements.

The Java Thread class implements Runnable. This is logical because the only purpose of a Thread is to execute some sequence of code, either once or repeatedly.

#### What is Provided by Runnable?

Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target. This was referred to as “Method 2” in Lesson 2.

Refresher

As a refresher, below is an example of what is being discussed:

    public class foo implements Runnable

     {

        ...

        public void run()

       {

           Thread t = new Thread(this);

       }
    }

#### The Run Method

The declaration of the run() method is as follows:

    public abstract void run()

This is the method that is executed when a Runnable object is activated. The run() method is the “soul” of a Thread. It is in this method that all of the action of a Thread takes place.

| The run() method is the “soul” of a Thread. It is in this method that all of the action of a Thread takes place.

Previous | Table of Contents | Next

Copyright © DDC Publishing

Products | Contact Us | About Us | Privacy | Ad Info | Home Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.