让线程睡眠30分钟

ven*_*esh 16 java multithreading thread-sleep

我想让我的线程等待30分钟.这样做有什么问题吗?

sam*_*ris 33

你可以让你的线程睡30分钟,如下所示:

Thread.sleep(30 *   // minutes to sleep
             60 *   // seconds to a minute
             1000); // milliseconds to a second
Run Code Online (Sandbox Code Playgroud)

使用Thread.sleep本身并不坏.简单地说,它只是告诉线程调度程序抢占线程.Thread.sleep错误使用时会很糟糕.

  • 在不释放(共享)资源的情况下休眠:如果您的线程正在与来自共享连接池的开放数据库连接或内存中的大量引用对象一起休眠,则其他线程无法使用这些资源.只要线程休眠,这些资源就会被浪费掉.
  • 用于防止竞争条件:有时你可以通过引入一个实际上解决竞争条件sleep.但这不是一种保证方式.使用互斥锁.请参阅Java中是否存在互斥锁?
  • 作为保证计时器:Thread.sleep不保证睡眠时间.它可能会过早地返回InterruptedException.或者它可能睡过头了.

    来自文档:

    public static void sleep(long millis) throws InterruptedException
    
    Run Code Online (Sandbox Code Playgroud)

    导致当前正在执行的线程休眠(暂时停止执行)指定的毫秒数,具体取决于系统计时器和调度程序的精度和准确性.


您也可以使用,正如kozla13在评论中所示:

TimeUnit.MINUTES.sleep(30);
Run Code Online (Sandbox Code Playgroud)

  • 更好的解决方案:TimeUnit.MINUTES.sleep(30); (8认同)

isn*_*bad 9

克鲁米亚的回答已经完美展示了跑步的方法Thread。有时,睡眠或暂停线程的要求源于希望在以后执行操作。如果是这种情况,您最好使用更高级别的概念,例如Timeror ScheduledExecutorService

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(operation, 30, TimeUnit.MINUTES);
Run Code Online (Sandbox Code Playgroud)

哪里operationRunnable你想在30分钟内执行。

使用 a ScheduledExecutorService,您还可以定期执行操作:

// start in 10 minutes to run the operation every 30 minutes
executor.scheduleAtFixedDelay(operation, 10, 30, TimeUnit.MINUTES);
Run Code Online (Sandbox Code Playgroud)