arjacsoh arjacsoh - 1 year ago 98
Java Question

Difference between notify() and notifyAll()

I know that similar questions have been discussed in this site, but I have not still got further by their aid considering a specific example. I can grasp the difference of notify() and

"awakeining" in theory but I cannot perceive how they influence the functionality of program when either of them is used instead of the other. Therefore I set the following code and I would like to know what is the impact of using each one of them. I can say from the start that they give the same output (Sum is printed 3 times).

How do they differ virtually? How could someone modify the program, in order for the applying notify or
to play a crucial role to its functionality (to give different results)?


class MyWidget implements Runnable {
private List<Integer> list;
private int sum;

public MyWidget(List<Integer> l) {
list = l;

public synchronized int getSum() {
return sum;

public void run() {
synchronized (this) {
int total = 0;
for (Integer i : list)
total += i;

sum = total;




public class MyClient extends Thread {
MyWidget mw;

public MyClient(MyWidget wid) {
mw = wid;

public void run() {
synchronized (mw) {
while (mw.getSum() == 0) {
try {
} catch (InterruptedException e) {
System.out.println("Sum calculated from Thread "
+ Thread.currentThread().getId() + " : " + mw.getSum());

public static void main(String[] args) {
Integer[] array = { 4, 6, 3, 8, 6 };
List<Integer> integers = Arrays.asList(array);

MyWidget wid = new MyWidget(integers);

Thread widThread = new Thread(wid);
Thread t1 = new MyClient(wid);
Thread t2 = new MyClient(wid);
Thread t3 = new MyClient(wid);



I write it explicitly. The result is the same whether one uses notify or notifyAll:
Sum calculated from Thread 12 : 27
Sum calculated from Thread 11 : 27
Sum calculated from Thread 10 : 27

Therefore my question: What is the difference?

Answer Source

I found what is going on with my program. The three Threads print the result even with the notify(), because they do not manage to enter the waiting state. The calculation in the widThread is performed quickly enough to preempt the entering of the other Threads in the waiting state, since it depends on the condition mw.getSum() == 0 (while loop). The widThread calculates the sum, so that the remaining Threads do not ever "see" its value as 0. If the while loop is removed and the start of widThread comes after the start of the other Threads, then by notify() only one Thread prints the result and the others are waiting forever, as the theory and the other answers indicate.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download