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.或者它可能睡过头了.
来自文档:
Run Code Online (Sandbox Code Playgroud)public static void sleep(long millis) throws InterruptedException导致当前正在执行的线程休眠(暂时停止执行)指定的毫秒数,具体取决于系统计时器和调度程序的精度和准确性.
您也可以使用,正如kozla13在评论中所示:
TimeUnit.MINUTES.sleep(30);
Run Code Online (Sandbox Code Playgroud)
克鲁米亚的回答已经完美展示了跑步的方法Thread。有时,睡眠或暂停线程的要求源于希望在以后执行操作。如果是这种情况,您最好使用更高级别的概念,例如Timeror ScheduledExecutorService:
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(operation, 30, TimeUnit.MINUTES);
Run Code Online (Sandbox Code Playgroud)
哪里operation是Runnable你想在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)
| 归档时间: |
|
| 查看次数: |
47335 次 |
| 最近记录: |