Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

notifyAll() example

 
Swerrgy Smith
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author
Sheriff
Posts: 8900
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Darren Littlepage
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic