0% found this document useful (0 votes)
2 views1 page

Threads and Concurrency Java Notes

Threads in Java are the smallest units of execution that enable concurrency, allowing multiple tasks to progress simultaneously. They can be created by extending the Thread class or implementing the Runnable interface, with synchronization necessary to prevent race conditions. While threads improve performance and responsiveness, they also introduce complexity and potential issues like deadlocks.

Uploaded by

Mehnaz Shoukat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views1 page

Threads and Concurrency Java Notes

Threads in Java are the smallest units of execution that enable concurrency, allowing multiple tasks to progress simultaneously. They can be created by extending the Thread class or implementing the Runnable interface, with synchronization necessary to prevent race conditions. While threads improve performance and responsiveness, they also introduce complexity and potential issues like deadlocks.

Uploaded by

Mehnaz Shoukat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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.

You might also like