Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

wait() or thread.sleep()

 
Jackie Davis
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, having read some of the other posts I am not sure which method to use. I want to be able to pause running through some code for 1000ms and then restart. I have two methods, one running straight after the other. I would like to be able to delay starting the 2nd method for a short period.

Thanks
 
IM Mahesh
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Difference in these APIs is that Thread.speep(long millis) causes to sleep the current thread for given period of time. It does not release the monitor which it has been aquired.. While Thread.wait(long millis) causes to wait for given period of time or will also exit from wait condn if any other thread calls Thread.notify() or Thread.notifyAll() on the same object on which this thread is synchronized. Also it releases the monitor that it has aquired.
Now in your case as you just want to pause the current thread for particular period of time should use Thread.speep(1000).
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by IM Mahesh:
Thread.speep(long millis) causes to sleep the current thread for given period of time. It does not release the monitor which it has been aquired.


Thread.sleep() does not acquire a lock. It has nothing to do with synchronisation.

If the code is holding any locks before sleep(), it still holds them during sleep(). It is often a bad idea to hold any locks during sleep.
 
IM Mahesh
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right Peter,
Sorry for the confusion happened. By mistake i was assuming that the sleep() method is going to be called in synchronized block, which is not always true.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic