java 无操作 休眠,让java程序在没有线程的情况下休眠

Dear 丶 2023-01-24 04:20 69阅读 0赞

![Image 1][]

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

解决方案

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.

[Image 1]:

发表评论

表情:
评论列表 (有 0 条评论,69人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java线休眠示例编程

    在Java编程中,线程休眠是一种常用的技术,用于暂停当前线程的执行一段时间。总结来说,线程休眠是Java编程中常用的技术之一,能够实现线程的暂停执行一段时间。通过本文提供...

    相关 Thread--线休眠sleep

    sleep()的作用是让当前线程进入休眠,当前线程会由运行状态进入到阻塞状态,sleep()可以指定休眠时间,休眠时间会大于等于该休眠时间,在线程被重新唤醒时,线程的状态由阻塞

    相关 线休眠

    线程对象一旦调用其`start`方法之后,就会运行,运行的就是`run`方法中的代码,等到`run`方法中的代码运行结束,线程就执行完成。