Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

wait and notify

 
marilyn murphy
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you always have to use synchronized when using wait and notify?

Do wait and notify always have to be used in the same class?
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by marilyn murphy:
Do you always have to use synchronized when using wait and notify?
Yes; if you don't have a lock on the object, they throw an IllegalMonitorStateException. See the javadoc for java.lang.Object.
Do wait and notify always have to be used in the same class?
Not necessarily in the same class, but you do have to use them on the same object because they have to operate on the same monitor lock.
- Peter
 
marilyn murphy
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So if I want to use them in two separate classes, would you recommend using a third (separate) object to lock on rather than trying to use "this" on the one and trying to pass that object somehow to the second class. Seems like it could get complicated.
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by marilyn murphy:
So if I want to use them in two separate classes, would you recommend using a third (separate) object to lock on rather than trying to use "this" on the one and trying to pass that object somehow to the second class. Seems like it could get complicated.


It all depends on what you want to wait on. Any thread can wait on ANY other object. This feature is baked into the "Object" class and as a result is in all classes. You can have 5 threads waiting on 1 object, or however you want to do it. Remember, the Threads are doing the waiting.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic