Runnable Interface

Package: java.lang

The Runnable interface describes a class whose instances can be run as a thread. The interface itself is very simple, describing only one method (run) that is called automatically by Java when the thread is started.

The Runnable interface is usually used in conjunction with the Thread class. For more information, see Thread Class.

Methods

Method

Explanation

void run()

Called when the thread is started. Place the code that you want the thread to execute inside this method.

To use the Runnable interface to create and start a thread, you have to do the following:

1. Create a class that implements Runnable .

2. Provide a run method in the Runnable class.

3. Create an instance of the Thread class and pass your Runnable object to its constructor as a parameter.

A Thread object is created that can run your Runnable class.

4. Call the Thread object’s start method.

The run method of your Runnable object is called and executes in a separate thread.

Here’s an example of a class that implements Runnable:

public class RunnableClass implements Runnable1

{

public void run()

{

// code to execute when thread is run

// goes here

}

}

Here’s an example that instantiates a RunnableClass object, and then creates a Thread object to run the RunnableClass object:

RunnableClass rc = new RunnableClass();

Thread t = new Thread(rc);

t.start();

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset