What are the different ways to create threads in Java?
Answered
What are the different ways to create threads in Java? Which is preferable and why?
Best answer
Threads in Java can be created in two ways:
- By inheriting from Thread class (extends Thread)
- By implementing Runnable interface (implements Runnable)
Implementing Runnable interface is preferred over extending Thread class because implementing Runnable interface allows to extend from other class and also implement Runnable interface. The Thread class itself implements Runnable interface.
By extending Thread class, each of your threads has a unique object associated with it, whereas by implementing Runnable, many threads can share the same object instance.