SystemClock.sleep()与视频下载()在等待一个信号量环 [英] SystemClock.sleep() vs. Thread.sleep() while waiting for a semaphore loop

查看:194
本文介绍了SystemClock.sleep()与视频下载()在等待一个信号量环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了同步到共享资源/队列的访问,我将使用的信号灯,通过等待循环辅助。

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

为了不碰到CPU挂,我想睡眠()里面那个有点,而循环。

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

我搜索 http://developer.android.com 参考,并发现了两个这样的睡眠()函数和我很困惑,哪个最适合哪一种情景:

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. 视频下载()

  2. SystemClock.sleep()

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

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

Which one better suits the case I described and why?

推荐答案

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

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

这是说,如果你真的想要一个轮询循环(这你真的,除非你有不应该这样做),我会用视频下载坚持()。没有太多的差别,因为文档中说,除了你必须中断Thread.sleep()方法的选项。不要摆脱自己做这样的选择。

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.

请注意,在Thread.sleep()方法的情况下,你将不得不捕获该异常 - 如果你是非常懒惰,你可能会与SystemClock.sleep()坚持

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().

这篇关于SystemClock.sleep()与视频下载()在等待一个信号量环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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