The Runnable Interface

An applet is created by extending the Applet or JApplet class; a class cannot be a subclass of more than one parent class, so we cannot extend the Thread class if we want to create a thread within an applet. To get around this, Java provides the Runnable interface. The interface is specified in the applet class declaration using the implements keyword, for example,

public class ThreadedNumbers extends Applet implements Runnable {

The Runnable interface consists of just one method, run, which takes no arguments. We create the run method within our applet subclass; the method contains the execution code for the thread similar to the run method for applications . We avoid having to subclass Thread by passing an instance of the applet subclass, this, to the newly created Thread object.

For example,

numbersThread = new Thread(this);

The thread is then started as follows:

numbersThread.start();

No comments:

Post a Comment