There are 2 ways to create a thread. One is to extend the Thread class overriding the run() method. The other is to implement the Runnable interface also overriding the run() method
Extending the Thread class:
public class MyClassThread extends Thread { @Override public void run() { System.out.println("In MyClassThread, Thread id = " + Thread.currentThread().getId()); } }
Use it in main:
public class MainClass { public static void main(String[] args) { MyClassThread myClassThread = new MyClassThread(); myClassThread.start(); try { myClassThread.join(); } catch (InterruptedException ie) { ie.printStackTrace(); } } }
Output:
In MyClassThread, Thread id = 20
Implementing the Runnable interface:
This is especially suitable if the class already extended another class. And due to Java not allowing extending multiple classes,
if the class already extended another class, then it cannot extend the Thread class anymore
The following MyChildClass is already extending a class, so we cannot make it extend Thread
public class MyChildClass extends MyParentClass { }
Instead just make it implements Runnable:
public class MyChildClass extends MyParentClass implements Runnable { @Override public void run() { System.out.println("In MyChildClass, Thread id = " + Thread.currentThread().getId()) ; } }
Use it in main:
public class MainClass { public static void main(String[] args) { Thread thread = new Thread(new MyChildClass()); thread.start(); try { thread.join(); } catch (InterruptedException ie) { ie.printStackTrace(); } } }
Output:
In MyClassThread, Thread id = 20
One thing to note, Runnable actually is a functional interface, so we could use Lambda expression:
public class MainClass { public static void main(String[] args) { Thread thread = new Thread(() -> { System.out.println("Using Lambda Expression, Thread id = " + Thread.currentThread().getId()); }); thread.start(); try { thread.join(); } catch (InterruptedException ie) { ie.printStackTrace(); } } }
Output:
Using Lambda Expression, Thread id = 20