Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads (wait & notify)

 
Rudolf Meerkotter
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

I came up with this bit of code below to practice wait() and notify(). Class Changeable has a boolean variable, notifies the Observer class from it's run method, which then stops waiting and prints Changeable's state. Observer checks for notifications from a while loop. All normal so far. When I run it, it seems that not all the notifications are received. Sometimes more, sometimes less, but never all.

Output varies, but looks like this:

Changeable running. State is: true 1
Changeable running. State is: true 2
Observer running. Changeable's state is true 1
Changeable running. State is: true 3
Observer running. Changeable's state is true 2
Changeable running. State is: true 4
Observer running. Changeable's state is true 3
Changeable running. State is: true 5
Changeable running. State is: true 6
Observer running. Changeable's state is true 4
Changeable running. State is: true 7
Observer running. Changeable's state is true 5
Changeable running. State is: true 8
Observer running. Changeable's state is true 6
Changeable running. State is: true 9
Observer running. Changeable's state is true 7
Changeable running. State is: true 10
Observer running. Changeable's state is true 8

Here's the code:
 
Henry Wong
author
Marshal
Pie
Posts: 21405
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a notification is sent, and there isn't a thread waiting for it, it will be lost.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic