Synchronization of Threads in Java unit 2
Synchronization of Threads in Java unit 2
If two threads access the same variable or object at the same time, it can lead to data
inconsistency.
t1.start();
t2.start();
t1.join();
t2.join();
t1.start();
t2.start();
t1.join();
t2.join();
Synchronization Types
Type Usage
Synchronized Method Synchronizes the whole method
Synchronized Block Synchronizes only a critical part
Static Synchronization Synchronizes static methods
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.
// 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();
}
}
}
// 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