Menu
- Home
- Java
- Multithreading
- Starting Threads
Starting Threads
Basic ways to start the threads in Java
Ways to Start a Thread
In Java, there are two primary ways to create a new thread:
- Extending the Thread class
- Implementing the Runnable interface
1. Extending the Thread Class
Steps for Thread Class
- Extend the Thread class
- Override the run method
- Create an instance of the class extending Thread
- Call the start method
class Runner extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Count: " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
public class Main {
public static void main(String[] args) {
Runner runnerOne = new Runner();
runnerOne.start();
Runner runnerTwo = new Runner();
runnerTwo.start();
}
}
2. Implementing the Runnable Interface
Steps for Runnable interface
- Implement the Runnable interface
- Override the run method
- Create a Thread instance and pass the Runnable implementation as an argument
- Call the start method of the Thread instance
class Runner implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Count: " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
public class Main {
public static void main(String[] args) {
Thread threadOne = new Thread(new Runner());
threadOne.start();
Thread threadTwo = new Thread(new Runner());
threadTwo.start();
}
}