javamultithreadingsleep

Make a java program sleep without threading


I have a java program that does some calculations and then uploads the results to a MYSQL database (hosted in another computer in the same network). I sometimes face the problem that the program does calculations faster than it uploads the result. Therefore it is not able to upload all the results. The program currently is not threaded.

Is there a way I can make the program sleep for a few milliseconds after it has done the calculations so that the upload takes place properly. (Like in other languages sleep or wait function)

I can thread the program but that will be too much rewriting. Is there an easier way?

Thanks


Solution

  • Is there a way I can make the program sleep for a few milliseconds after it has done the calculations so that the upload takes place properly. (Like in other languages sleep or wait function)

    Thread.sleep(milliseconds) is a public static method that will work with single threaded programs as well. Something like the following is a typical pattern:

    try {
        // to sleep 10 seconds
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        // recommended because catching InterruptedException clears interrupt flag
        Thread.currentThread().interrupt();
        // you probably want to quit if the thread is interrupted
        return;
    }
    

    There is no need to implement Runnable or do anything else with thread calls. You can just call it anytime to put a pause in some code.