This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Getting MEAN with Mongo, Express, Angular, and Node and have Simon Holmes on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread.sleep() and lock 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 "Thread.sleep() and lock" Watch "Thread.sleep() and lock" New topic
Author

Thread.sleep() and lock

Suleyman Suleymanov
Greenhorn

Joined: Nov 26, 2010
Posts: 3
hello.can anyone help me with this code? it seems like thread does release lock when it enters to sleep mode when i uncomment the try-catch block.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19716
    
  43

Suleyman Suleymanov wrote:hello.can anyone help me with this code? it seems like thread does release lock when it enters to sleep mode when i uncomment the try-catch block.


That's correct. The Thread.sleep() method doesn't release any locks. Were you under the impression that it does? Perhaps you are confusing the sleep() method with the wait() method?

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Suleyman Suleymanov
Greenhorn

Joined: Nov 26, 2010
Posts: 3
when i uncomment the try-catch block i get this output :
0 t1
0 t2
1 t1
1 t2
2 t1
2 t2
3 t1
3 t2
4 t2
4 t1
5 t2
5 t1
6 t2
6 t1
7 t1
7 t2
8 t2
8 t1
9 t1
9 t2
doesn't it mean that t1 release lock when it goes to sleep and t2 get the lock?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19716
    
  43

Suleyman Suleymanov wrote:when i uncomment the try-catch block i get this output :
0 t1
0 t2

doesn't it mean that t1 release lock when it goes to sleep and t2 get the lock?


Oh... I am sorry. I misread your question...

No. Thread.sleep() does *not* release any locks. The reason that the two threads are interlacing is because the two threads are using two different locks.

Henry
Suleyman Suleymanov
Greenhorn

Joined: Nov 26, 2010
Posts: 3
thanks.i got it.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Thread.sleep() and lock