让线程睡眠30分钟 [英] Making a Thread to Sleep for 30 minutes

查看:887
本文介绍了让线程睡眠30分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to make my thread to wait for 30 minutes. Are there any problems of doing this?

推荐答案

你可以让你的线程像这样睡30分钟:

You can make your thread sleep for 30 minutes like this:

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

使用 Thread.sleep 是本质上不是坏事。简单地说,它只是告诉线程调度程序抢占线程。错误地使用<$ p $ c> Thread.sleep 是坏的。


  • 睡觉不释放(共享)资源:如果您的线程因共享连接池中的开放数据库连接或内存中的大量引用对象而休眠,则其他线程无法使用这些资源。只要线程休眠,这些资源就会被浪费。

  • 用于阻止竞争条件 :有时你可以通过引入 sleep 来实际解决竞争条件。但这不是一种保证方式。使用互斥锁。请参阅 Java中是否存在Mutex?

  • 作为保证计时器:无法保证 Thread.sleep 的休眠时间。它可能会以 InterruptedException 过早返回。或者它可能睡过头了。

  • 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.

来自文档


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 已在评论中显示:

You could also use, as kozla13 has shown in their comment:

TimeUnit.MINUTES.sleep(30);

这篇关于让线程睡眠30分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆