Threads In Java.
Thread In Java π§΅
Java Threads
Threads help a software to work more effectively by allowing it to do numerous tasks at once.
Threads allow complex activities to be completed in the background without interrupting the main programme.
Creating a Thread
A thread could be made in two ✌ ways.
It's possible to create one by extending the Thread class and overriding the run() method.
Another way to create a thread is to implement the Runnable interface.
Running Threads
Extend Example :
public class Main extends Thread { public static void main(String[] args) { Main thread = new Main(); thread.start(); System.out.println("This code is outside of the thread"); } public void run() { System.out.println("This code is running in a thread"); } }Implement Example :
public class Main implements Runnable { public static void main(String[] args) { Main obj = new Main(); Thread thread = new Thread(obj); thread.start(); System.out.println("This code is outside of the thread"); } public void run() { System.out.println("This code is running in a thread"); } }
Threads: The Differences Between "Extending" and "Implementing"π―
The main difference is that a class that extends the Thread class cannot
extend any other class, whereas a class that implements the Runnable
interface can extend from any other class, such as: class MyClass extends
OtherClass implements Runnable.
πΈπΈπΈππΈπΈπΈ
