Creating a Java Thread by implementing Runnable Interface

Creating a Java Thread by implementing Runnable Interface

Let us now create a sample Fibonacci Program using threads that generates Fibonacci series. This program creates the thread by extending thread class:
 OUTPUT
To crate threads, create a new class that extends the Thread class, and instantiate that class. The extending class must override the run() method and call start() method to begin execution of the thread.
1)If you want to extend the Thread class then it will make your class unable to extend other classes as java is having single inheritance feature whereas If you implement runnable interface, you can gain better object-oriented design and consistency and also avoid the single inheritance problems.
2)Extending the thread will give you simple code structure in comparison to Runnable Interface.
3)Using Runnable Interface, you can run the class several times whereas Thread have the start() methodthat can be called only once
If you have had created a thread class by extending Thread class, you could have directly called start() method as t.start (), where t is a thread object. This is because thread class created by extending Thread class is a subclass of  Thread class, so it has all functionalities of a thread. While creating a thread implementing Runnable, a Thread object will have to be explicitly created which is what PrintFibo class is doing. It then passes JavaFib object as a parameter to this thread and runs it. This causes the run ( ) method of JavaFib class to get executed.
Now will rewrite the code by implementing Runnable Interface :
 In general, I would recommend using something like Runnable rather than Threadbecause it allows you to keep your work only loosely coupled with your choice of concurrency. For example, if you use a Runnable and decide later on that this doesn’t in fact require it’s own Thread, you can just call threadA.run().
Runnable because:
  • •Leaves more flexibility for the Runnable implementation to extend another class
  • •Separates the code from execution
  • •Allows you to run your runnable from a Thread Pool, the event thread, or in any other way in the future.
  • Even if you don’t need any of this now, you may in the future. Since there is no benefit to overriding ThreadRunnable is a better solution.

0 comments:

Post a Comment