How many ways can I create a thread in Java?
How many ways can I create a thread in Java?
There are 2 ways to create thread in java.
1. Using the Thread class.
2. Using the Runnable Interface.
Below are the examples:
1. Using the Thread class.
1. Using the Thread class.
public class ThreadDemo1 {
public static void main(String[] args) {
Printer1 thread1 = new Printer1();
thread1.setName("Simple Thread");
thread1.start();
}
}
class Printer1 extends Thread{
@Override
public void run() {
System.out.println("Inside "+Thread.currentThread().getName());
}
}
Here you can see that we extends the Thread class and implements its run method.
We have to create thread class object and call the start() method of it to start the execution of the thread.
2. Using the Runnable Interface.
public class ThreadDemo2 {
public static void main(String[] args) {
Printer2 task = new Printer2();
Thread thread2 = new Thread(task);
thread2.setName("Runnable Thread");
thread2.start();
}
}
class Printer2 implements Runnable {
@Override
public void run() {
System.out.println("Inside " + Thread.currentThread().getName());
}
}
Here you can she that we implements the Runnable class and to execute thread we need to create the Thread class object and call the start method of it.
Even you are using Runnable interface you have to create the object of thread class.
Comments
Post a Comment