Wait-Notify-And-Notifyall

This is Sixth Article in Series of Articles on Java 8 Concurrency Tutorial.

In this article, we will look at one of the most basic methods of Java-thread synchronization.

Object Class in Java has three final methods to allow threads to communicate about the lock status of the threads.

These methods are wait(), notify() and notifyAll().

wait()

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

notify()

Wakes up a single thread that is waiting on this object’s monitor.

notifyAll()

Wakes up all threads that are waiting on this object’s monitor.

Let’s try to implement Producer & Consumer problem using wait(),notify()& notifyAll();

Producer will add number in List. List can have maximum 5 numbers . Consumer will remove elements from list until it becomes empty.

Volatile Keyword Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
 
package com.nirajsonawane;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

class Processor {

private List<Integer> list = new ArrayList<>();
private Random random = new Random();

public synchronized void producer() {

while (true) {
try {
Thread.sleep(1000);
if (list.size() == 5) {
System.out.println("List is full Notifying Consumer & Releasing Lock");
notifyAll();
wait();
}
while (list.size() < 5) {
System.out.println("Adding items");
list.add(random.nextInt());
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

public synchronized void consumner() {
while (true) {

try {
Thread.sleep(1000);
if (list.isEmpty()) {

System.out.println("List is Empty :Notifying Publisher & Releasing Lock");
notifyAll();
wait();
} else {
System.out.println("Size of list " + list.size() + " Removed Number is " + list.remove(0));
}

} catch (Exception e) {
// TODO: handle exception
}
}
}
}

public class WaitNotifyNotifyAllExample {

public static void main(String[] args) throws InterruptedException {
Processor p = new Processor();
Thread t1 = new Thread(() -> p.producer());
Thread t2 = new Thread(() -> p.consumner());
t1.start();
t2.start();
t1.join();
t2.join();
}

}

Share Comments