Threads and Concurrency in Java
Definition
A thread is the smallest unit of execution in a Java program. Concurrency means multiple tasks
making progress during the same time period.
Why Threads?
Improve responsiveness, perform background work, and utilize CPU efficiently.
Creating Threads
1. Extend Thread class.
2. Implement Runnable interface (recommended).
class MyThread extends Thread {
public void run(){ [Link]("Running"); }
}
public class Test{
public static void main(String[] a){
MyThread t=new MyThread();
[Link]();
}
}
class Task implements Runnable{
public void run(){ [Link]("Task"); }
}
Synchronization
Synchronization prevents multiple threads from accessing shared data at the same time, avoiding
race conditions.
class Counter{
private int count=0;
public synchronized void increment(){ count++; }
}
Key Terms
Race Condition: incorrect result due to simultaneous access.
Deadlock: threads wait forever for each other.
Thread Life Cycle: New, Runnable, Running, Blocked/Waiting, Terminated.
Advantages: Better performance, responsiveness, resource sharing.
Disadvantages: Complexity, deadlocks, synchronization overhead.
Exam Points
Use start() to begin a thread; run() contains task code. Prefer Runnable for flexibility. Use
synchronized to protect shared resources.