Thread example for Runnable Interface



Runnable Interface : The easiest way to create a thread is to create a class that implements the Runnable interface. Runnable abstracts a unit of executable code. You can construct a thread on any object that implements Runnable. To implement Runnable, a class need only implements a single method called run(), which is declared like this.

public void run()

Inside run(),you will define the code that constitutes the new thread. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can. The only difference is that run() establishes the entry point for another, concurrent thread of execution within your program. This thread will end when run() returns.

After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here:

Thread(Runnable threadOb, String threadName)

In the constructor, threadOb is an instance of a class that implements the Runnable interface. This defines where execution of the thread will begin. The name of the new thread is specified by threadName.

After the new thread is created, it will not start running until you call its start() method, which is declared within Thread. In essence, start() executres a call to run().

The start() method is shown here:

void start()

Here is an example that creates a new thread and starts it running:

Ex:#1;

//Create a second thread.

class NewThread implements Runnable{

Thread t;
NewThread(){

//Create a new, second thread
t=new Thread(this,”Demo Thread”);
System.out.println (“Child Thread:”+t);
t.start();  //Start the thread.
}

//This is the entry point for the second thread,

public void run() {
try{
for(int i=5;i>0;i–)  {
System.out.println(“Child Thread:”+i);
Thread.sleep(500);
}
}catch(InterruptedException e){
System.out.println(“Child interrupted.”);
}
System.out.println(“Exiting child thread.”);
}
}

class ThreadDemo {
public static void main(String args[]) {
new NewThread();  //create a new thread
try{
for(int i=5;i>0;i–)  {
System.out.println(“Main Thread:”+i)
Thread.sleep(1000);
}
}catch(InterruptedException e) {
System.out.println(“Main thread interrupted.”);
}
System.out.println(“Main thread exisiting.”);
}
}

Share with SociBook.com

Random Posts

  1. 1 Comment(s)

  2. By EmpareKeefe on Aug 15, 2011 | Reply

    I’m brand new,This really is my first come to here.I hope everyone can help me.

    You will find item and support data for the TVs on arithmetic sequence.

Post a Comment