让线程休眠30分钟

24

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


1
是的,有很多问题,因为您的线程将在30分钟内什么也不做。Thread.sleep(1000 * 60 * 30);,并将其包装在try-catch中。 - Kon
5
不要睡眠一个线程,尝试使用计时器。 - Rod_Algonquin
1
@Kon - 为什么一个休眠的线程会引发“大量问题”? - Ted Hopp
2
在我看来,这是一个糟糕设计的标志。虽然它可能不会在代码执行中引起问题,但使用定时器或类似的东西来实现你的目标几乎总是更好的选择。 - Kon
1
第二部分的问题无法回答。什么会被视为“问题”? - Raedwald
显示剩余6条评论
2个回答

44
您可以通过以下方式使线程休眠30分钟:

Thread.sleep(30 *   // minutes to sleep
             60 *   // seconds to a minute
             1000); // milliseconds to a second

使用 Thread.sleep 并不是固有的坏事。简单来说,它只是告诉线程调度程序要抢占该线程。当 Thread.sleep 被错误使用时,它就变得不好了。

  • Sleeping without releasing (shared) resources: If your thread is sleeping with an open database connection from a shared connection pool, or a large number of referenced objects in memory, other threads cannot use these resources. These resources are wasted as long as the thread sleeps.
  • Used to prevent race conditions: Sometimes you may be able to practically solve a race condition by introducing a sleep. But this is not a guaranteed way. Use a mutex. See Is there a Mutex in Java?
  • As a guaranteed timer: The sleep time of Thread.sleep is not guaranteed. It could return prematurely with an InterruptedException. Or it could oversleep.

    From documentation:

    public static void sleep(long millis) throws InterruptedException
    

    Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.


您可以像kozla13在评论中展示的那样使用:
TimeUnit.MINUTES.sleep(30);

11
更好的解决方案:TimeUnit.MINUTES.sleep(30);(意为让程序暂停执行30分钟) - kozla13
1
在 Java 19+ 中,您也可以使用以下代码:Thread.sleep(Duration.ofMinutes(30)) - yurez

10

Krumia已经完美地展示了如何让运行中的Thread休眠。有时,暂停或休眠线程的需求来自于希望在稍后时间执行操作的愿望。如果是这种情况,最好使用像TimerScheduledExecutorService这样的更高级别概念:

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(operation, 30, TimeUnit.MINUTES);

当您想在30分钟内执行Runnable时,您可以使用ScheduledExecutorService,也可以定期执行操作:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接