Friday 28 February 2014

Creating Thread by implementing Runnable interface

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.

Runnable interface has only one method, i.e., run().

Prototype of run method is

public void run();

Example
class MyThread implements Runnable{
 public void run(){
  System.out.println("I am in run method");
 }

 public static void main(String args[]){
  MyThread task = new MyThread();
  Thread t1 = new Thread(task);
  t1.start();
 }
}

Output
I am in run method

Advantages of creating thread using Runnable as compared to extending Thread

1. By using runnable, you can create a task, and make number of threads to call it.
Example
class MyThread implements Runnable{
 public void run(){
  System.out.println("I am in run method");
 }

 public static void main(String args[]){
  MyThread task = new MyThread();
  Thread t1 = new Thread(task);
  Thread t2 = new Thread(task);
  t1.start();
  t2.start();
 }
}

Output
I am in run method
I am in run method


2. If you create a thread by extending Thread class, then you are not allowed to extend any other class. Since java doesn't support multiple inheritance.


Create Thread by extending Thread class                                                 Exploring Thread API                                                 Home

No comments:

Post a Comment