Threading
Threading
● Efficient resource use, such as using idle CPU time while waiting on I/O.
🧵 What Is a Thread?
A thread is a lightweight unit of a process. All threads of a process share the same memory but
execute independently. In Java, threads can be created in two main ways:
java
CopyEdit
class MyThread extends Thread {
public void run() {
System.out.println("Running in a thread");
}
}
Use:
java
CopyEdit
new Thread(new MyRunnable()).start();
● Thread Scheduling: Managed by JVM and OS; thread priorities can be set but not
guaranteed.
● Thread Safety: Ensuring shared resources are accessed safely (avoid race conditions).
🔒 Synchronization
When multiple threads access shared data, synchronization ensures that only one thread at a
time can execute a critical section.
java
CopyEdit
synchronized void increment() {
count++;
}
Other tools:
● ReentrantLock
● AtomicInteger
🛠️ java.util.concurrent Utilities
Java provides high-level concurrency tools:
🧠 Benefits of Multithreading
● Better CPU utilization
❌ Common Pitfalls
● Race conditions: Two threads updating shared data simultaneously.
✅ Summary
● Java supports multithreading at the language and library level.
● Threads can improve performance but require careful handling of shared data.
● Synchronization, locks, and concurrent utilities help manage thread safety and
coordination.