Java Thread Example by extending Thread class
Java Thread Example by implementing Runnable interface
So we can use "Runnable" interface, it will help us inherit another class, because if we use "Thread" inheritance then we should loose one scope to inherit another class if we need.
package com.pkm; import java.util.Date; /** * Created by pritom on 31/10/2017. */ public class ThreadTest extends Thread { public static void main(String[] args) throws Exception { System.out.println("Thread called at = " + (new Date())); new ThreadTest().start(); } public void run() { try { sleep(10000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread executed at = " + (new Date())); } }
Java Thread Example by implementing Runnable interface
package com.pkm; import java.util.Date; /** * Created by pritom on 31/10/2017. */ public class RunnableTest implements Runnable { public static void main(String[] args) throws Exception { System.out.println("Thread called at = " + (new Date())); new Thread(new RunnableTest()).start(); } @Override public void run() { try { Thread.sleep(10000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread executed at = " + (new Date())); } }
So we can use "Runnable" interface, it will help us inherit another class, because if we use "Thread" inheritance then we should loose one scope to inherit another class if we need.