wood burning stoves 2.0*
The moose likes Threads and Synchronization and the fly likes wait and notify Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "wait and notify" Watch "wait and notify" New topic
Author

wait and notify

marilyn murphy
Ranch Hand

Joined: Aug 28, 2001
Posts: 84
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

Joined: Apr 20, 2000
Posts: 3252
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

Joined: Aug 28, 2001
Posts: 84
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

Joined: Oct 05, 2001
Posts: 1170

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: wait and notify