Tuesday, August 2, 2016

Different Ways to Create Thread in Java


Java defines two ways by which a thread can be created.
  • By implementing the Runnable interface.
  • By extending the Thread class.
 Implementing the Runnable Interface
The easiest way to create a thread is to create a class that implements the runnable interface. After implementing runnable interface, the class needs to implement the run() method, which is of form,
public void run()
  • run() method introduces a concurrent thread into your program. This thread will end when run() returns.
  • You must specify the code for your thread inside run() method.
  • run() method can call other methods, can use other classes and declare variables just like any other normal method.
class MyThread implements Runnable
{
 public void run()
 {
  System.out.println("concurrent thread started running..");
 }
}
class MyThreadDemo
{
 public static void main( String args[] )
 {
  MyThread mt = new MyThread();
  Thread t = new Thread(mt);
  t.start();
 }
}
Output :
concurrent thread started running..

To call the run() method, start() method is used. On calling start(), a new stack is provided to the thread and run() method is called to introduce the new thread into the program.

Extending Thread class
This is another way to create a thread by a new class that extends Thread class and create an instance of that class. The extending class must override run() method which is the entry point of new thread.
class MyThread extends Thread
{
 public void run()
 {
  System.out.println("Concurrent thread started running..");
 }
}
classMyThreadDemo
{
 public static void main( String args[] )
 {
  MyThread mt = new  MyThread();
  mt.start();
 }
}Output :
concurrent thread started running..

In this case also, as we must override the run() and then use the start() method to start and run the thread. Also, when you create MyThread class object, Thread class constructor will also be invoked, as it is the super class, hence MyThread class object acts as Thread class object.

What if we call run() method directly without using start() method ?
In above program if we directly call run() method, without using start() method,
public static void main( String args[] )
{
 MyThread mt = new MyThread();
 mt.run();
}
Doing so, the thread won't be allocated a new call stack, and it will start running in the current call stack, that is the call stack of the main thread. Hence Multithreading won't be there.

Can we Start a thread twice ?
No, a thread cannot be started twice. If you try to do so, IllegalThreadStateException will be thrown.
public static void main( String args[] )
{
 MyThread mt = new MyThread();
 mt.start();
 mt.start();     //Exception thrown
}
When a thread is in running state, and you try to start it again, or any method try to invoke that thread again using start() method, exception is thrown.


Differences Between Extends Thread and Implements Runnable In Java:
1) Multiple Inheritance Limitation
As you know, Java doesn’t support multiple inheritance. A class in java can extend only one class. If you extend Thread class, then your class will not be able to extend any other class. This will limit your class to thread behaviour. If you implement Runnable interface, then you will have an option for your class to extend any other class and inherit behaviours from other class also.

2) Overhead of Additional Methods
If you extend Thread class, all methods of Thread class will be inheriting to your class which you may not need. This will cause additional overhead. You can remove this overhead by implementing Runnable interface.

3) Logical Separation of Task from The Runner
If you implement Runnable interface, it will separate actual task from the runner. Runnable interface represents only the task and you can pass this task to any type of runner, either a thread or any executors.

4) Best Object Oriented Design Practice
In object oriented programming, extending a class means modifying or improving the existing class. If you are not improving the class, then it is not a good practice to extend it. So, implementing Runnable will be the best object oriented design practice.

5) Loosely Coupled Vs Tightly coupled
“Implements Runnable” makes your code loosely coupled. Because it separates the task from the runner. “Extends Thread” will make your code tightly coupled. Because, single class will act as both task container as well as runner.

6) Reusability
Implementing Runnable improves the reusability of your code. Because, Runnable contains only the task and you can use it wherever and whenever you want.

7) Specialization Vs Generalization
“Extends Thread” gives more specialized code. Because, it defines the thread specific task. Whereas “Implements Runnable” gives more generalized version of the task applicable to many threads.

8) Maintenance

“Implements Runnable” will make your code easily maintainable as it separates the task from the runner. If you want to modify the task at any time, you can do so easily without disturbing the runner.

No comments:

Post a Comment