Meaningless Drivel is fun!*
The moose likes Threads and Synchronization and the fly likes Thread without sleep? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Thread without sleep?" Watch "Thread without sleep?" New topic
Author

Thread without sleep?

CongSon Nguyen
Greenhorn

Joined: Nov 17, 2010
Posts: 4


When we use Thread, we should call Thread.sleep() so that other thread has a chance to execute. However, in my simple app above, I do not need to use Thread.sleep(...), but both thread still have a chance to execute. So, why is it ? Is it because of multicore in my CPU ? If so, we do not need to use Thread.sleep(...). Can anyone please help me ? Thanks a lot.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18846
    
  40

CongSon Nguyen wrote:
When we use Thread, we should call Thread.sleep() so that other thread has a chance to execute.


Where did you hear this? ... because this is simply not true.


It may have been somewhat true, back with the early JVMs, when it was implemented on top of a user threading library (green threads). However, even with green threads, this was only true if you were completely compute intensive -- it did scheduling when you made library calls, like the system out IO calls.

Henry


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

Joined: Nov 17, 2010
Posts: 4
I still don't get it. Can you please explain more clearly ?

Java.sun.com said "Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system".
Even when we don't use Thread.sleep(...), processor time is still available to the other threads -> I do not really understand it.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  16

No, what they probably mean is that you should use Thread.sleep() instead of some busy wait (looping in code that does nothing until a certain amount of time has elapsed).
 
 
subject: Thread without sleep?