What are Multithreading and Concurrency in Java?
Multithreading allows multiple threads (lightweight processes) to execute concurrently, improving application performance and responsiveness.
1. Extending Thread Class
class MyThread extends Thread {
private String threadName;
MyThread(String name) {
threadName = name;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " - Count: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted");
}
}
System.out.println(threadName + " finished");
}
public static void main(String[] args) {
MyThread t1 = new MyThread("Thread-1");
MyThread t2 = new MyThread("Thread-2");
t1.start();
t2.start();
System.out.println("Main thread continues...");
}
}
2. Implementing Runnable Interface (Recommended)
class Counter implements Runnable {
private String name;
Counter(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + ": " + i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Counter("Counter-1"));
Thread t2 = new Thread(new Counter("Counter-2"));
t1.start();
t2.start();
// Wait for threads to finish
t1.join();
t2.join();
System.out.println("Both threads finished");
}
}
Synchronization (Thread Safety)
Prevents race conditions when multiple threads access shared resources.
class BankAccount {
private double balance = 1000;
// Synchronized method - only one thread can access at a time
public synchronized void withdraw(double amount) {
if (balance >= amount) {
System.out.println(Thread.currentThread().getName() + " withdrawing " + amount);
balance -= amount;
System.out.println("Remaining balance: " + balance);
} else {
System.out.println("Insufficient balance for " + Thread.currentThread().getName());
}
}
public static void main(String[] args) {
BankAccount account = new BankAccount();
Runnable task = () -> account.withdraw(300);
Thread t1 = new Thread(task, "User-1");
Thread t2 = new Thread(task, "User-2");
Thread t3 = new Thread(task, "User-3");
t1.start();
t2.start();
t3.start();
}
}
Thread Lifecycle
class ThreadLifecycle {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
System.out.println("Thread running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("State after creation: " + t.getState()); // NEW
t.start();
System.out.println("State after start: " + t.getState()); // RUNNABLE
Thread.sleep(500);
System.out.println("State during sleep: " + t.getState()); // TIMED_WAITING
t.join();
System.out.println("State after completion: " + t.getState()); // TERMINATED
}
}
Producer-Consumer Example
class SharedResource {
private int data;
private boolean available = false;
public synchronized void produce(int value) throws InterruptedException {
while (available) {
wait();
}
data = value;
available = true;
System.out.println("Produced: " + data);
notify();
}
public synchronized void consume() throws InterruptedException {
while (!available) {
wait();
}
System.out.println("Consumed: " + data);
available = false;
notify();
}
}
Thread Pool (Executor Framework)
import java.util.concurrent.*;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 10; i++) {
final int taskId = i;
executor.submit(() -> {
System.out.println("Task " + taskId + " executed by " +
Thread.currentThread().getName());
});
}
executor.shutdown();
}
}
Master multithreading and concurrency with Online Learner!
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
