Tuesday, August 17, 2010

Java Thread's Runnable Interface

A thread can be run in two ways, using  Thread class and Runnable Interface.   Like extending a Thread class, the use of Runnable interface allows us to execute the run method through the invocation of start ( ). But, unlike Thread where we simply make an instance of the class, a runnable interface allows to create an object of Thread class and associate this with our Runnable object.

A program below creates 3 threads of S - T - I (along with the main method as another thread) using Runnable.

[+/-] show/hide

class PrintName implements Runnable{
Thread thread;

PrintName(String name)
{ thread = new Thread(this, name);
//implements run() method defined in the Runnable interface
public void run()
String name=thread.getName();
for(int i = 0; i<10;i++)

System.out.print(name); }

public class ThreadRunnable2{
public static void main (String [] args){
//since the constructor of the PrintName
//object creates a Thread object and
//starts it, there is no need to do it here

new PrintName("S");
new PrintName("T");
new PrintName("I"); } }

No comments: