0% found this document useful (0 votes)
2 views

Synchronization of Threads in Java unit 2

Synchronization in Java controls access to shared resources by multiple threads to prevent race conditions and data inconsistency. Java provides synchronization through the 'synchronized' keyword for methods and code blocks, ensuring that only one thread can access a resource at a time. Inter-thread communication is facilitated using wait-notify mechanisms, allowing threads to coordinate actions, particularly in producer-consumer scenarios.

Uploaded by

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

Synchronization of Threads in Java unit 2

Synchronization in Java controls access to shared resources by multiple threads to prevent race conditions and data inconsistency. Java provides synchronization through the 'synchronized' keyword for methods and code blocks, ensuring that only one thread can access a resource at a time. Inter-thread communication is facilitated using wait-notify mechanisms, allowing threads to coordinate actions, particularly in producer-consumer scenarios.

Uploaded by

arpitsharma1263
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Synchronization of Threads in Java

Synchronization in Java is a mechanism to control access to shared resources by multiple


threads. It prevents race conditions, where two or more threads try to modify the same
resource simultaneously.

Why Synchronization is Needed?

If two threads access the same variable or object at the same time, it can lead to data
inconsistency.

How Java Provides Synchronization

Java uses the synchronized keyword to:

 Make a method synchronized.


 Make a block of code synchronized (within a method).

Example Without Synchronization (Problematic)


class Counter {
int count = 0;

public void increment() {


count++;
}
}

public class UnsynchronizedDemo {


public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();

Thread t1 = new Thread(() -> {


for(inti = 0; i< 1000; i++) counter.increment();
});

Thread t2 = new Thread(() -> {


for(inti = 0; i< 1000; i++) counter.increment();
});

t1.start();
t2.start();
t1.join();
t2.join();

System.out.println("Final count (expected 2000): " + counter.count);


}
}
Output may be less than 2000 because threads overwrite each other.

Example With Synchronization (Corrected)


class Counter {
int count = 0;

public synchronized void increment() {


count++;
}
}

public class SynchronizedDemo {


public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();

Thread t1 = new Thread(() -> {


for(inti = 0; i< 1000; i++) counter.increment();
});

Thread t2 = new Thread(() -> {


for(inti = 0; i< 1000; i++) counter.increment();
});

t1.start();
t2.start();
t1.join();
t2.join();

System.out.println("Final count (expected 2000): " + counter.count);


}
}

Output will always be 2000, thanks to synchronized.

Synchronization Types

Type Usage
Synchronized Method Synchronizes the whole method
Synchronized Block Synchronizes only a critical part
Static Synchronization Synchronizes static methods

Inter-Thread Communication in Java

Inter-thread communication in Java allows multiple threads to communicate and


coordinate with each other using wait-notify mechanisms. It is often used in producer-
consumer problems where threads share a common resource.
Key Methods (Defined in Object class)

Method Description
wait()
Causes the current thread to wait until another thread calls notify() or
notifyAll() on the same object.
notify() Wakes up one thread waiting on the object's monitor.
notifyAll() Wakes up all threads waiting on the object's monitor.

These methods must be called inside a synchronized block or method.

Simple Example: Inter-thread Communication


classSharedResource {
boolean flag = false;

// Producer
synchronized void produce() {
try {
if (flag) wait(); // wait if already produced
System.out.println("Producing...");
flag = true;
notify(); // notify consumer
} catch (InterruptedException e) {
e.printStackTrace();
}
}

// Consumer
synchronized void consume() {
try {
if (!flag) wait(); // wait if nothing to consume
System.out.println("Consuming...");
flag = false;
notify(); // notify producer
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class InterThreadExample {


public static void main(String[] args) {
SharedResource res = new SharedResource();

// Producer thread
Thread producer = new Thread(() -> {
for (inti = 0; i< 5; i++) {
res.produce();
}
});

// Consumer thread
Thread consumer = new Thread(() -> {
for (inti = 0; i< 5; i++) {
res.consume();
}
});

producer.start();
consumer.start();
}
}

Output:
Producing...
Consuming...
Producing...
Consuming...
...

Important Notes

 Always use wait(), notify(), notifyAll() within a synchronized context.


 Otherwise, you'll get IllegalMonitorStateException.

You might also like