Java Thread with Runnable interface


In the previous chapter Multi Threading we saw how to create a thread by extending the Thread class.

Creating Java Thread with Runnable interface.

2. Implement Runnable

package com.hunaid.thread;

public class RunnableThread implements Runnable {
 public void run() {

  System.out.println("MyThread run called");
  for(int i=0;i<=5;i++){
   System.out.println(i);
  }
 
 }
}
The class here looks very similar to the class in the previous chapter where we extended the Thread class. It is just that instead of extending the Thread class we are implementing Runnable interface. This is a better design as now we can also extend some other class if we want.

The Thread class actually implements Runnable interface and provides a empty implementation. Start method though is the part of Thread class and not Runnable.

To test this class lets create a class


package com.hunaid.thread;

public class ThreadTest {

 public static void main(String args[]){
  RunnableThread  runnableThread = new RunnableThread();
  Thread thread = new Thread(runnableThread);
  thread.start();
  System.out.println("Runnable thread started");
 }
}


Here we have first created istance of RunnableThread class. But like MyThread in previous chapter we can not call the start method directly on it. We then created a instance of Thread class and passed the instance of RunnableThread in the constructor of it. Then we called the start method on the instance of Thread.

Lets run the class and print the output.


Thread class  >>  Runnable Interface >>  Callable Interface   >>  CountDownLatch   >>  CyclicBarrier   >>  Semaphore   >>  Reentrant Lock   >>  Reentrant Lock with Condition

6 comments:

Share the post