Menus

Dec 24, 2018

Explain different ways of creating a thread.Which one would you prefer and why ?


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
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();
}
}

#Extending Thread class
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();
}
}

I would prefer creating thread by Implementing the Runnable Interface because of following reasons:

1) If class A extends class Thread then class A cannot not extend other class and vice-versa.
2) Thread class has lots of methods in it so if we extend Thread class then our class gets all the methods(unnecessary burden) of Thread class that we are not going to use.

No comments:

Post a Comment

Contact Form

Name

Email *

Message *