Multithreading in Java allows users to perform multitasking with minimum shared memory area. Multithreading in Java is supported through the Thread class and Runnable interface. They both are very important in the world of multithreading and they serve different purposes and use cases. In this article, we will discuss about difference between Threads and Runnable with examples.
Thread Concept:
Thread is the smallest unit of the process that allows a program to run efficiently by performing multi-tasking. When a class extends the Thread class, it becomes thread. It provides methods to create and control more threads. Run() method is used to perform actual needed work. This method must be overridden by the class extending Thread.
Consider the following example.
In the above example, MyThread extends the Thread class and overrides the run() method. The thread is started using the start() method, allowing both the main thread and MyThread instance to execute.
Runnable Interface:
It is an interface used to perform code on concurrent threads. Runnable interface has an abstract method called run().To use Runnable, a class must implement the Runnable interface and provide an implementation for the run method.
Consider the following example.
In the above example, the MyRunnable class implements the Runnable interface. An instance of MyRunnable is then passed to the Thread constructor, and the thread is started, resulting in concurrent execution of the main thread and MyRunnable instance.
Difference Between Thread and Runnable:
Extending Vs. Implementing: A class extending Thread can not extend any other class, limiting flexibility. On the other hand, the class can implement multiple interfaces and also allowing to implement Runnable and extend other class if required.
Reusability: The concept of Reusability is achievable by using Runnable. Code becomes more modular. With thread, threads are tightly coupled in a single class, limiting reusability.
Resource Sharing: With Thread, each thread has its own instance which leads to increased memory consumption. Implementing Runnable is a preferred approach when multiple threads share resources.
Thread Pooling: Executor framework is used in Java for managing and controlling thread execution. It becomes easier to work with thread pools when we implement Runnable.
Conclusion:
In conclusion, Thread and Runnable offer unique advantages and use cases. When choosing between two, developers can identify their requirements according to the application and can consider any from Thread and Runnable.
Comments