Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

One Question about Thread

 
Richard Wilson
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Answer:C,D
I think C,D is contradictory.
Why C,D is right while B is wrong.
 
Stephen Batsas
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Richard
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
B,C
regards
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13056
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
NO NO NO!
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.
Bill
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic