Thread is a independent path of execution within a program.
There are two ways to create a thread:
1. By extending the Thread class.
Thread class provide constructors and methods to create and perform operations on a thread. This class implements the Runnable interface. When we extend the class Thread, we need to implement the method run(). Once we create an object, we can call the start() of the thread class for executing the method run().
Eg:
class MyThread extends Thread {
public void run() {
for(int i = 1;i<=20;i++) {
System.out.println(i);
}
}
public static void main(String a[]) {
MyThread t = new MyThread();
t.start();
}
}
a. By implementing the runnable interface.
Runnable interface has only on one method- run().
Eg:
class MyThread implements Runnable {
public void run() {
for(int i = 1;i<=20;i++) {
System.out.println(i);
}
}
public static void main(String a[]) {
MyThread m = new MyThread();
Thread t = new Thread(m);
t.start();
}