• 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

synchronized

 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Read the following code, which is a part of a synchronized method of a monitor.

public synchronized void someMethod()
{
//lots of code
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
//do some crap here.
}
//more and more code here
}
When the thread "goes to sleep" it releases the lock on the object.
The "sleeping" Threads always have the lock on the Object.
the ans is 2nd. why not the first? but if call Thread.wait();should the ans be the first one?
 
High Plains Drifter
Posts: 7289
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Once a thread enters a synchronized method, it has acquired the lock for that object instance. sleep() has no impact on locking whatsoever; which is why it's not a good idea to sleep with a lock in the first place.
wait() is not a Thread method -- a frequent misconception among beginners -- it's an Object method. This will make more and more sense with practice; threads call wait() on objects, not themselves.
In this code snippet, the lock is only released by exiting the method.
------------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic