Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Sleeping  RSS feed

 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are there any problems running a thread that never sleeps?
For example, say I had something like this:
PSEUDO CODE

Is it necessary for this thread to sleep to give other threads a chance to run? Or does it matter?
Thanks,
Drew
 
Joe Ess
Bartender
Posts: 9406
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Drew Lane:
Are there any problems running a thread that never sleeps?

Only if you want to do something at the same time. Really that's only half true as the Java Virtual Machine will preempt a running thread for a thread of greater priority. The operating system and hardware influence thread behavior as well (i.e. time slicing, multiple processors). Check out the Java Tutorial chapter on Threads, specifically Understanding Thread Priority. It has some excercises that may enlighten you.
 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, the main reason I was asking is because I have some code in my thread that may stop running for short periods of time (depending on user interaction), but I still want to keep the thread running instead of spawning a new thread. So far, this has been working. I figure I'll just keep this thread running until the user quits the application.
However, I was thinking maybe I should add a sleep method when the thread is not doing any work? It sounds like this is only necessary when I have other threads that need a piece of the pie.
BTW, I don't have any other threads running at this time (beside the main application thread and the AWT thread, etc.).
Regards,
Drew
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you can use Thread.sleep() or Object.wait() to avoid a so-called busy or tight loop, you should. Tight loops steal processor cycles and then just waste them, slowing down your software and your entire system. At the very least you can usually get away with something like this (depending on the nature of the system):

Although Object.wait() is quite effective for having your threads sleep until some condition is satisfied.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!