There are two ways to create threads in Java
- By implementing Runnable interface
- By extending the Thread Class
public class ThreadCreationDemo { public static void main(String[] args) { // Create threads by instantiating extended Thread class ThreadByThreadClass t1 = new ThreadByThreadClass(); t1.setName("t1"); // Sets name of thread ThreadByThreadClass t2 = new ThreadByThreadClass(); t2.setName("t2"); // Sets name of thread // Create threads by instantiating Thread class by passing Runnable as argument Thread t3 = new Thread(new ThreadByRunnableInterface(),"t3"); Thread t4 = new Thread(new ThreadByRunnableInterface(),"t4"); t1.start(); t2.start(); t3.start(); t4.start(); } } class ThreadByRunnableInterface implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } } } class ThreadByThreadClass extends Thread { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } } }
Difference between Thread and Runnable
- Preferred way of creating threads is by implementing Runnable interface. Through this we are not really modifying the behavior of thread. We are just submitting a task to the thread to execute.
- Java only supports single inheritance, so we can loose the leverage of extending another class if create thread by extending Thread class.
- Implementing an interface gives a cleaner separation between our code.
- By implementing Runnable interface, we actually create a task which can be passed to Executor service to execute but created threads by extending Thread class cannot be used with Executor service.
Favor Composition over Inheritance