How To Create Thread In Java ?
We can create thread in two ways :
1.By Extending Thread Class
2.By Implementing Runnable Interface.
Example of Creating Thread By Extending Thread class :
public class MyThread extends Thread {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
thread1.start();
}
@Override
public void run() {
System.out.println("Thread 1 is started");
}
}
Output:Thread 1 is started
Example of Creating Thread by implementing Runnable Interface :
public class ThreadDemo implements Runnable {
public static void main(String[] args) {
ThreadDemo td=new ThreadDemo();
Thread myThread=new Thread(td);
myThread.start();
}
@Override
public void run() {
System.out.println("Thread is started");
}
}
Output: Thread is started