Threads can be used by either:
- Extending the Thread class.
- Implementing the Runnable interface.
Using the Executor framework (this creates a thread pool)
By extends:
class Counter extends Thread {
//method where the thread execution will start
public void run(){
//logic to execute in a thread
}
//let’s see how to start the threads
public static void main(String[] args){
Thread t1 = new Counter();
Thread t2 = new Counter();
t1.start(); //start the first thread. This calls the run() method.
t2.start(); //this starts the 2nd thread. This calls the run() method.
}
}
By implements:
class Counter extends Base implements Runnable{
//method where the thread execution will start
public void run(){
//logic to execute in a thread
}
//let us see how to start the threads
public static void main(String[] args){
Thread t1 = new Thread(new Counter());
Thread t2 = new Thread(new Counter());
t1.start(); //start the first thread. This calls the run() method.
t2.start(); //this starts the 2nd thread. This calls the run() method.
}
}
The thread pool is more efficient and learn why and how to create pool of threads using the executor framework.