Is it effective to keep Java programs running indefinitely?

My program starts with main and starts some threads to execute the program work (reading sensors, updating databases, and displaying information to the screen) I want the program to run indefinitely

At the moment after my main thread starts, I only have:

public static void main(String []args)
{
    //threads start here
    while(true) {}
}

Obviously this is effective, but I wonder if it wastes resource recycling

Is there an effective way to keep the program running Is there an elegant exit? That is, start an event listener listening for keyboard or events in main?

If it's better, I've tried this:

while(true) {
    TimeUnit.HOURS.sleep(1);
}

Edit: more about threads:

I'm not sure what kind of threads they are I'm implementing a program called GNU io. The interface of serialporteventlistener, which starts and processes threads, so it is abstracted from me I'll have to look at the API, although I don't think it's well documented, or I think it's source code They keep the JVM active in the IDE (BlueJ), but not when running programs on the command line I just use the interface method to add an event listener to a COM port where the starting thread runs

Solution

Unless your thread is a daemon thread, I don't understand why you should have a period of time or that problem will only occupy your CPU The main thread is not terminated unless all non daemon threads are completed In addition, if you want to clean up, you can register the JVM's close hook

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>