1. What is Multithreading?
Multithreading is a concurrent execution technique where multiple threads
run independently but share the same resources, such as memory space.
Each thread performs a different task in the program simultaneously,
improving performance, especially on multi-core processors.
A thread is a lightweight process, and a Java program can have multiple
threads that run concurrently.
2. Thread Class and Runnable Interface
There are two main ways to create threads in Java:
o Extending the Thread class
o Implementing the Runnable interface
Using the Thread Class
You can create a thread by creating a subclass of the Thread class and
overriding its run() method.
Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
, thread.start(); // start() invokes the run() method
}
}
Using the Runnable Interface
You can also create a thread by implementing the Runnable interface and
passing an instance of the class to a Thread object.
Example:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
3. Thread Lifecycle
A thread in Java can be in one of the following states:
o New: The thread is created but not yet started.
o Runnable: The thread is ready to run and is waiting for CPU time.
o Blocked: The thread is waiting for a resource (like I/O operations or
synchronization).
o Waiting: The thread is waiting indefinitely for another thread to
perform a specific action.
o Terminated: The thread has finished executing.