My program starts in main, and fire off a few threads that do the work of the program (reading sensors, updating a database, displaying information to a screen). I want the program to run indefinitely.
At the moment after my threads have started in main I just have:
public static void main(String []args)
{
//threads start here
while(true) {}
}
Obviously this works but I am wondering if it is wasting resources looping.
Is there an efficient way to keep the program running. Is there a graceful way to exit? i.e. start an event listener in main that listens for a keyboard or event or something?
I also tried this if it is any better:
while(true) {
TimeUnit.HOURS.sleep(1);
}
EDIT: more info regarding the threads:
I'm not sure what type of thread they are. I am implementing an interface called gnu.io.SerialPortEventListener, that starts and handles the threads, so its abstracted away from me. I'll have to have a look at the API, although I think it isn't well documented, or look at the source I guess. They keep the JVM alive in the IDE (blueJ) but not when I run the program on the command line. I just use the interface's method to add an event listener to a com port which starts the threads running.
Unless your threads are daemon threads I don't see why you should have a while or for that matter any loops which would just eat your CPU. Your main thread will not be killed unless all non daemon threads are completed. Also if you wish to do cleanup you can register a JVM's shutdown hook.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With