In Java multi-threading can be achieved in two ways.
Let’s look at them one by one.
Extending Thread class
While we extend our custom thread with Thread class, we need to override run() method. All the code that is supposed to run in a separate thread, is put in the run() method. Then we can simple call start() method on our object.
Here is how to extend Thread class:
public class MyThread extends Thread { @override public void run() { try { System.out.println ("Thread has started"); } catch (Exception e) { System.out.println (e.printStackTrace()); } } }
Here is how to start the thread:
public class MutithreadingDemo { public static void main (String[] args) { MyThread thread = new MyThread(); thread.start(); } }
Implementing Runnable interface
We implement Runnable interface in our class, keeping the code, we want to run in a separate thread, in run() method that comes with the interface. Then, to start a thread, we create an object of Thread class which takes an object of type Runnable. We pass an object of our custom runnable to it, and simple call start() on the thread object.
Here is how to implement Runnable:
public class MyRunnable implements Runnable { @override public void run() { try { System.out.println ("Runnable has started using a thread"); } catch (Exception e) { System.out.println (e.printStackTrace()); } } }
Here is how to start a thread with Runnable object.
public class MutithreadingDemo2 { public static void main (String[] args) { MyRunnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); thread.start(); } }
Now as we have seen two different ways to start a thread, you might be wondering which is better.
As such, both ways are almost similar in the sense that we need a Thread object to start anyway. However, in case of second approach, we need to create an object of our Runnable implementation which has the actual code.
As you know, Java does not allow multiple inheritance through class, so if you choose the first approach, your class can not extend anymore classes, and when you need to, you are stuck. But hey, here comes the second approach to the rescue. You can always extend another class with your Runnable implementation.