等待信号量循环时的 SystemClock.sleep() 与 Thread.sleep()

发布于 2024-11-04 04:52:36 字数 598 浏览 0 评论 0原文

为了同步/排队对共享资源的访问,我将使用 信号量,由等待循环辅助。

为了不遇到 CPU 挂钩问题,我想在 while 循环中稍微休眠一下。

我搜索了 http://developer.android.com 参考文献,发现了两个这样的 sleep() 函数,我很困惑哪个适合哪种情况:

  1. Thread.sleep()
  2. SystemClock.sleep()

哪一个更适合我描述的情况,为什么?

In order to synchronize/queue access to a shared resource, I am about to use a Semaphore, aided by a wait loop.

In order not to run into CPU pegging, I would like to sleep() a little bit inside that while loop.

I searched the http://developer.android.com reference and found two such sleep() functions and I am confused as to which one fits which scenario:

  1. Thread.sleep()
  2. SystemClock.sleep()

Which one better suits the case I described and why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浮光之海 2024-11-11 04:52:36

首先,你真的需要等待循环吗?您通常可以使用适当的通知来解决问题,即拥有一个对象,对其调用 wait()notify() 或其他方式(例如阻塞队列,或< code>Semaphore.acquire() 在你的情况下)。

也就是说,如果您确实想要一个轮询循环(除非必须,否则您真的不应该这样做),我会坚持使用 Thread.sleep() 。正如文档所说,没有太大区别,只是您可以选择中断 Thread.sleep() 。不要放弃这样做的选择。

请注意,如果使用 Thread.sleep(),您将必须捕获该异常 - 如果您非常懒,您可能会坚持使用 SystemClock.sleep() 。

First of all, do you really need a wait loop? You can typically solve your problems using proper notifications, i.e. having an Object, calling wait() and notify() on it or other means (like a blocking queue, or Semaphore.acquire() in your case).

That said, if you really want a polling loop (which you really shouldn't do unless you have to), I'd stick with Thread.sleep(). There's not much of a difference, as the documentation says, except that you have the option to interrupt a Thread.sleep(). Don't rid yourself the option to do so.

Note that in case of Thread.sleep(), you're going to have to catch that exception - if you're extremely lazy, you'll probably stick with SystemClock.sleep().

独孤求败 2024-11-11 04:52:36

事实是:

Thread.sleep(n) 可以通过使用 asyncTask.cancel(true) 在像 AsyncTask 这样的调用中被中断

SystemClock.sleep(n) 似乎会忽略任何中断的命令,因此当您像这样使用它: https://github.com/square/leakcanary/blob/master/leakcanary-sample/src/main/java/com/example/leakcanary/MainActivity.java

The truth is:

Thread.sleep(n) could be interrupted within a call like AsyncTask by using asyncTask.cancel(true)

SystemClock.sleep(n) seems to ignore any interrupted command, thus it could be a risk of memory leak when you use it similar like here: https://github.com/square/leakcanary/blob/master/leakcanary-sample/src/main/java/com/example/leakcanary/MainActivity.java

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文