How anyone can write an Indefinite running Thread without a costly loop like while?
Like I don’t want something like this
public void run() {
while(true)
{
do Blah Blah Blah
Thread.sleep(.....);
}
}
Any optimized way to write such a long running thread.
Thanks in advance.
In what way do you consider
while(true)“costly”? Do you have any evidence that this is affecting your performance? What operation would you consider to be cheaper than it?Note that from your comment:
it sounds like you’re considering the whole loop, not the
whilepart. So let’s look at what you’re doing in the loop:You’re explicitly telling the thread to sleep. While it’s sleeping, it won’t be consuming CPU resources. So no, it’s not costly. Admittedly if your sleep period is very short and your “do Blah Blah Blah” is very quickly, you’ll be looping an awful lot – but in that case you should consider increasing the sleep time. (You should also consider other approaches which allow you to signal to the thread that you wish it to quit cleanly, and do so even while it’s sleeping, without having to interrupt the thread.)
You haven’t given us any information about what you’re really trying to achieve, but fundamentally the use of
whileisn’t a problem here. Just think about how often you want to loop, and whether it’s really a simple time-based value. For example, if this thread is meant to process work, then perhaps you want a producer/consumer queue of some description – there’s no need for the thread to sleep while it has work to do, but there’s no need for it to wake up until there’s work to do. That’s only an example, of course – without more information we really can’t give much more advice.