我想让我的线程等待30分钟。这样做有什么问题吗?
Thread.sleep(30 * // minutes to sleep
60 * // seconds to a minute
1000); // milliseconds to a second
使用 Thread.sleep
并不是固有的坏事。简单来说,它只是告诉线程调度程序要抢占该线程。当 Thread.sleep
被错误使用时,它就变得不好了。
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.
TimeUnit.MINUTES.sleep(30);
Thread.sleep(Duration.ofMinutes(30))
。 - yurezKrumia已经完美地展示了如何让运行中的Thread
休眠。有时,暂停或休眠线程的需求来自于希望在稍后时间执行操作的愿望。如果是这种情况,最好使用像Timer
或ScheduledExecutorService
这样的更高级别概念:
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);
Thread.sleep(1000 * 60 * 30);
,并将其包装在try-catch中。 - Kon