• Post Reply Bookmark Topic Watch Topic
  • New Topic

Wait() doubt  RSS feed

 
John Lincoln
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Is this legal and "right" way of using wait()?
try{
while (true){
System.out.println(" I am in wait loop :");
wait();
}
}catch(InterruptedException ie){//some function}
Or should i use wait only with notify?
If i just want to "wait" until i get interrupted , i should only as below ?
try{
Thread.sleep();
}catch (InterruptedException e){}
please help
Thanks for your time.
Praveen.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you really want to wait for an interrupt and never are going to notify the thread, I think you'd best use sleep(long) instead (with a very long sleep time). The reason for suggesting this is simply that anyone reading your code, upon seeing wait(), will automatically assume there is a notify() somewhere.
However, I'd want to query whether interrupt() is really the way to do whatever it is you want to do. Is there any reason why you can't use notify() instead of interrupt()?
- Peter
[ February 25, 2003: Message edited by: Peter den Haan ]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason for suggesting this is simply that anyone reading your code, upon seeing wait(), will automatically assume there is a notify() somewhere.
That, and also using a wait() requires you to first acquire a lock on the monitor instance whose wait() is invoked. In the code example shown, this can be achieved by making the enclosing method synchronized, or by using a smaller synchronized block (synchronized (this)). If your design doesn't otherwise have a need to acquire a lock, why add one now? Just use sleep() as Peter says. Or, use wait()/notify() instead of sleep()/interrupt() (again as Peter says). Which one to use depends on your requirements. But wait() almost always goes with notify()/notifyAll(), while sleep() may work well with interrupt(). Mixing them up is not very common.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!