SystemClock.sleep() vs. Thread.sleep() while waiting for a semaphore loop

后端 未结 2 1771
别跟我提以往
别跟我提以往 2020-12-31 16:24

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 t

相关标签:
2条回答
  • 2020-12-31 16:53

    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

    0 讨论(0)
  • 2020-12-31 16:57

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

    0 讨论(0)
提交回复
热议问题