Example of How to use a Runnable object in Java

Before executing a Runnable object using a Thread, there are a few steps that must be taken. First off, we must have a class that implements the Runnable interface – something that looks like this example class:

class Koala implements Runnable
{
  public void run()
  {
    System.out.println("climb"); 
  }
}

Create an instance of the class that implements Runnable

The next step is to create an instance of the class that implements Runnable. That would look like this example:

Koala bear = new Koala();

An example of passing Runnable object into Thread constructor

Then, the next step is to create a Thread object and pass the Runnable object (“bear”, in our example above) into the Thread constructor. The Runnable object will then become the target of the Thread’s execution. Here is an example of how passing the Runnable object into a Thread constructor would look:

Koala bear = new Koala();

//remember that Koala implements Runnable
//so bear is a Runnable object
//and bear is a target of Thread:

Thread threadObj = new Thread(bear);

Example of calling the start method on Thread

The final step is to call the start method on the Thread. The run method of the target (bear) will be called asynchronously. Thread’s run method will not be used. Here’s an example of what that would look like:

Koala bear = new Koala();
Thread threadObj = new Thread(bear);

/*
The start method that we defined earlier in the
Koala class will be called here, asynchronously:
*/

threadObj.start();






Follow Varoon Sahgal, author, on Google Plus