Threads in Java allow a program to execute multiple tasks simultaneously.
Java provides two main ways to create threads:
(i) By Extending the Thread Class:
You create a subclass of
Thread and override its
run() method.
Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}
Then create and start the thread using:
new MyThread().start();
(ii) By Implementing the Runnable Interface:
You create a class that implements
Runnable and define the
run() method.
Example:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread running...");
}
}
To execute:
new Thread(new MyRunnable()).start();
This method is preferred when the class already extends another class.