We can create thread in the following two ways .
1) By extending Thread class
2) By implementing Runnable interface
In this tutorial we are going to learn how to create thread by implementing Runnable interface .
Creating thread by implementing Runnable interface :
We can create thread by implementing Runnable interface also . Runnable interface present in java.lang package and contains run() method alone. If we implement Runnable interface , it is mandatory to override run() method in our class .
package com.java.jigi; class RunnableImpl implements Runnable { public void run() { for (int i = 0; i < 10; i++) { System.out.println(i); } } } public class RunnableExample { public static void main(String as[]) { Thread t = new Thread(new RunnableImpl()); t.start(); } }
See the above exmaple, when you call start() method then thread executes run() method and prints 0 1 2 3 ..9. Never override start() method in your class . If you override start() , then your start() will be executed rather than run() method . If you call run() method rather than start(), It will be executed as normal method calling .
Between above two approaches “implementing runnable interface” is best approach. If we extend Thread class, we can’t extend any othere class.