Threads in Java
Introduction
A thread in Java is a lightweight process. It is the smallest unit of execution in a program. Java supports
multithreading, allowing multiple threads to run concurrently, improving performance and responsiveness.
Ways to Create Threads
1. Extending the Thread class:
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
2. Implementing the Runnable interface:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread running");
Thread Lifecycle
1. New - Thread is created.
2. Runnable - Thread is ready to run.
3. Running - Thread is executing.
4. Waiting/Blocked - Thread is waiting for a resource.
5. Terminated - Thread has finished execution.
Common Thread Methods
start() - Starts the thread.
run() - Contains the code to be executed.
Threads in Java
sleep(ms) - Pauses thread for specified time.
join() - Waits for thread to finish.
interrupt() - Interrupts the thread.
Example
class MyThread extends Thread {
public void run() {
for(int i=1; i<=5; i++) {
try { Thread.sleep(500); } catch(Exception e) {}
System.out.println(i);
public static void main(String args[]) {
MyThread t1 = new MyThread();
t1.start();