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

thread that sleeps and thread that waits

 
Moni Patil
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the differences between
a thread that sleeps by calling sleep
and
a thread that waits by calling wait.
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A sleeping thread will wake after the amount of time specified in the sleep call, and will then resume execution.
A thread that called wait will not execute until a corresponding notify call is made by some other thread. That could happen almost immediately after calling wait, or it could happen much later, or maybe never.
So the difference is sleeping for a fixed amount of time vs. sleeping until an external event occurs.
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java has an API that you can read on Suns website or download yourself. I like to download the API myself because its very useful. If you read it you will have the answers you seek.

sleep does not release any held monitors but wait does.
 
Jignesh Patel
Ranch Hand
Posts: 626
Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sleep does not release any held monitors but wait does.

If you can elaborate more?
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thread.Sleep(long)
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

Object.wait(long)
Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

wait() must be called from within a synchronize block, and when its called it releases the synchronization lock bka monitor. sleep() has nothing to do with synchronization and does not affect any monitors.
 
Jignesh Patel
Ranch Hand
Posts: 626
Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lamont,
Gotcha. Thank you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic