It's not a secret anymore!
The moose likes Java in General and the fly likes notifyAll() example Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "notifyAll() example" Watch "notifyAll() example" New topic

notifyAll() example

Swerrgy Smith
Ranch Hand

Joined: Mar 26, 2010
Posts: 91
Dear all,

In the book of K&B, there is an example about how to use notifyAll() for thread communication. However, in the class Calculator below, if I remove the notifyAll(), the program stills works well. Can anybody tell me why?

And here is the result, it's the same with or without notifyAll().

Bert Bates

Joined: Oct 14, 2002
Posts: 8898
This topic is no longer on the SCJP 6 exam. It might still be on the SCJP 5 exam, but really, it's hard to imagine a good reason to take the SCJP 5 exam at this point, so let's move it and the discussion can be continued in Java in General.

Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
Darren Littlepage
Ranch Hand

Joined: Dec 27, 2010
Posts: 35
Specifically, what part of this is not on the exam? Threads, synchronized, wait() and notifyAll()? I understood serialization was not longer on the exam and I am familiar with the updated objectives. Is there anything new on the exam that is not covered in K&B SCJP 6? Sorry if this is out of scope of the topic. I have been studying threads a lot for the exam...regardless I know it will be helpful in the real world but my focus is to pass the exam.

OCPJP for Java 6 on 01/2011
Deepak Chopra
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

This is actually a very simple example.

3 threads are running all on same instance, which means - synchronized(this) means same for all threads. Lets say we have T-1, T-2,T-3 as threads and C-1 is calculator instance. Let assume that -
> T-2 got the lock over C-1, this leads to T-1 and T-3 both on waiting stage.
> T-2 finishes the calculation and released the lock over C-1. Now you can do either of two things-
1) Notify all the other threads waiting for C-1, by calling C-1.notifyAll( ) or this.notifyAll( ). order of T-1 and T-3 will be random. could be either T-1 then T-3 or vice versa.
2) Leave it as it is, in this case JVM will schedule the running of threads by its own. order of T-1 and T-3 will be random. could be either T-1 then T-3 or vice versa.


Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
I agree. Here's the link:
subject: notifyAll() example
It's not a secret anymore!