等待信号量循环时的 SystemClock.sleep() 与 Thread.sleep()
为了同步/排队对共享资源的访问,我将使用 信号量,由等待循环辅助。
为了不遇到 CPU 挂钩问题,我想在 while
循环中稍微休眠一下。
我搜索了 http://developer.android.com 参考文献,发现了两个这样的 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:
Which one better suits the case I described and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,你真的需要等待循环吗?您通常可以使用适当的通知来解决问题,即拥有一个对象,对其调用
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()
andnotify()
on it or other means (like a blocking queue, orSemaphore.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 aThread.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 withSystemClock.sleep()
.事实是:
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