File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes One Question about Thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "One Question about Thread" Watch "One Question about Thread" New topic

One Question about Thread

Richard Wilson
Ranch Hand

Joined: Jan 12, 2002
Posts: 57
Hi,look at code below:
1. public synchronized void someMethod() {
2. //lots of code
3. try {
4. Thread.sleep(500);
5. } catch(InterruptedException e) {
6. //do some things here.
7. }
8. //more and more code here
9. }
Select all correct answers
A.The code causes compiling error--can not call sleep inside synchronized method
B.The thread sleep at least 500 milliseconds if not interrupted
C.When the thread goes to sleep,it releases the lock on the object
D.The "Sleeping" thread always have the lock on the Object
I think C,D is contradictory.
Why C,D is right while B is wrong.

Richard Wilson
Stephen Batsas
Ranch Hand

Joined: Jan 22, 2002
Posts: 117
Once you call sleep the thread releases the lock on the object. The thread is in the blocking state. If the thread is not interrupted it will sleep for 500 milliseconds before going back to the ready state.
Not 100% sure but it seems the correct answer is
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13036
Calling sleep() does NOT release the lock. ONLY wait() releases the lock and puts the Thread in a special wait state.
B and D are correct.
Roy Ben Ami
Ranch Hand

Joined: Jan 13, 2002
Posts: 732
actually i think u r wrong Stephen.
here is what the API says:
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors.

so it doesnt give up the monitor. d is right therefore. and not c.also i think b is right.
I agree. Here's the link:
subject: One Question about Thread
It's not a secret anymore!