• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Thread.Sleep

 
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Found this on a mock exam......
public synchronized void someMethod()
{
//lots of code
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{ }

}
1. The code causes compilation error - sleep cannot be called inside synchronized methods.
2. The code causes compilation error - sleep is not a static method of java.lang.Thread
3. The Thread sleeps for at least 500 milliseconds in this method if not interrupted.
4. When the thread "goes to sleep" it releases the lock on the object.
5. The "sleeping" Threads always have the lock on the Object.
The answer given is 3 & 5. I didn't find this correct.... I think the answer is 3 & 4 as a Thread does give up the lock on an object if it goes to sleep.
Can somebody please verify this..???
Thanks,
Shafeeq
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Nope. A thread will give up a lock when it calls the wait() method, but not for sleep().
 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
..and what about the yeild() method? Does it give up the lock in the synchronized code? I think it does.

Originally posted by Jim Yingst:
Nope. A thread will give up a lock when it calls the wait() method, but not for sleep().


 
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
IMHO
Nope, Thread.yield() does NOT give up the monitor either!
 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yup, yield() will only let another thread work on, has nothing to do with the lock on the object.
Regards,
Khalid
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic