Multithreading and Concurrency in Java
Multithreading and Concurrency in Java
Multithreading and concurrency are core features of Java that allow you to build efficient, high-performing, and responsive applications. They enable a program to do multiple tasks at once by running different parts of code in parallel.
๐ง What Is Multithreading?
Multithreading is the ability of a CPU (or a single core) to provide multiple threads of execution within a process.
A thread is a lightweight subprocess — the smallest unit of processing.
Java allows multiple threads to run concurrently within the same program.
๐ฆ Key Concepts
Concept Description
Thread A unit of execution inside a program
Process A program in execution (may have multiple threads)
Concurrency Multiple tasks making progress (not necessarily at the same time)
Parallelism Tasks executed at the same time (requires multiple cores/CPUs)
๐ ️ Creating Threads in Java
1. Extending the Thread class
java
Copy
Edit
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // starts the new thread
}
}
2. Implementing the Runnable interface
java
Copy
Edit
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread running");
}
}
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}
⚙️ Thread Lifecycle
New – Thread is created.
Runnable – Ready to run.
Running – Currently executing.
Blocked/Waiting – Waiting for a resource or signal.
Terminated – Completed or killed.
๐ Thread Methods
Method Description
start() Starts the thread
run() Defines the thread’s task
sleep(ms) Pauses thread for given time
join() Waits for a thread to die
yield() Pauses to let other threads execute
๐งต Synchronization (Handling Shared Resources)
To prevent race conditions and ensure thread safety, Java provides synchronization.
java
Copy
Edit
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
๐งฐ Concurrency Utilities (java.util.concurrent)
Java provides advanced utilities for concurrency:
1. ExecutorService
Manages thread pools.
java
Copy
Edit
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> System.out.println("Task 1"));
executor.submit(() -> System.out.println("Task 2"));
executor.shutdown();
}
}
2. Callable and Future
Use when you need to return a result from a thread.
java
Copy
Edit
Callable<Integer> task = () -> 42;
Future<Integer> future = executor.submit(task);
Integer result = future.get(); // blocks until result is available
3. Locks and Semaphores
For advanced thread control.
✅ Best Practices
Avoid using raw threads for large applications — use Executors instead.
Minimize the use of synchronized blocks for better performance.
Always shut down thread pools to release resources.
Use thread-safe collections like ConcurrentHashMap.
๐ง Summary
Feature Use For
Thread, Runnable Basic multithreading
ExecutorService Managing thread pools efficiently
Callable, Future Returning results from threads
synchronized Thread-safe access to data
java.util.concurrent Advanced concurrency control
Learn Full Stack JAVA Course in Hyderabad
Read More
Java Collections Framework: List, Set, Map
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment