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

13 comments:

  1. This is really nice. Thanks for sharing this useful information and that's great one.

    ReplyDelete
  2. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.
    digital training in chennai

    ReplyDelete
  3. Useful queries.. thanks for sharing

    Best in salesforce Online Training Hyderabad@Capitalinfo solutions
    slaesforce online training

    ReplyDelete
  4. Informative and impressive. Keep Updating
    Jobvermittlung

    ReplyDelete
  5. Interesting post! This is really helpful for me. I like it! Thanks for sharing!
    seo l├╝denscheid

    ReplyDelete
  6. Thanks For Your valuable posting, it was very informative
    suchmaschinenmarketing l├╝denscheid

    ReplyDelete
  7. This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post. sua chua laptop da nang

    ReplyDelete

Share the post