Difference bewteen notify() and notifyAll()

Joined
Oct 22, 2007
Messages
2
Reaction score
0
I am new to the java world. I couldn't get a satisifying answer for difference between notify() , notifyAll().
To my understanding notify() should send notification to only one of the waiting threads and notifyAll() to all those waiting threads.
In my below example , i am using ONLY notify() but still other threads are gettign notified.

Please do help me in understanding why notify() is sending notification to all waiting threads.

Many thanks in advance.

CODE:

------
// reader class

class Reader extends Thread
{
Caliculator calc;

public Reader (Caliculator c)
{
calc = c;
}

public void run()
{
synchronized(calc)
{
try
{
System.out.println(Thread.currentThread().getName( ) + " is waiting ....");
calc.wait();
System.out.println(Thread.currentThread().getName( ) + " got notified ..");
System.out.println(Thread.currentThread().getName( ) + " - total : " + calc.sum);

}
catch(InterruptedException ie) {}
}

}

public static void main(String [] args)
{
Caliculator cal = new Caliculator();
Reader r1 = new Reader(cal);
r1.setName("Reader-1");
Reader r2 = new Reader(cal);
r2.setName("Reader-2");
Reader r3 = new Reader(cal);
r3.setName("Reader-3");

cal.start();
r1.start();
r2.start();
r3.start();



System.out.println("Program ends here");
}
}

//caliculator class

class Caliculator extends Thread
{
int sum=0;
public void run()
{
synchronized(this)
{
for (int index=0;index < 100 ; index++)
{
sum +=index;
}
try
{
Thread.sleep(2000);
}
catch(InterruptedException ex)
{
}

notify();
}
}
}

------------------------------------------------------------------------

output:


Reader-1 is waiting ....
Reader-2 is waiting ....
Reader-3 is waiting ....
Reader-2 got notified ..
Reader-2 - total : 4950
Reader-1 got notified ..
Reader-1 - total : 4950
Reader-3 got notified ..
Reader-3 - total : 4950

----------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top