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

To synchronize / distribute access to a shared resource, I am going to use Semaphore using a wait loop.

In order not to start binding to the processor, I would like a little sleep() inside the while .

I searched for the link http://developer.android.com and found two such sleep () functions, and I am confused as to which one is suitable for this scenario:

Which is better for the case I described and why?

+8
android multithreading sleep thread-sleep
source share
3 answers

First of all, do you really need a wait loop? You can usually solve your problems using the correct notifications, that is, have an object, call wait () and notify () on it or other means (for example, a blocking queue or Semaphore.acquire () in your case).

However, if you really need a polling cycle (which you really don't need to do if you don't need it), I would stick with Thread.sleep (). There is not much there, as the documentation says, except that you have the option to abort Thread.sleep (). Do not get rid of the opportunity to do this.

Note that in the case of Thread.sleep (), you will have to catch this exception - if you are very lazy, you will probably stick with SystemClock.sleep ().

+18
source share

Thread.sleep () is a function provided by java. InterruptedException may occur while calling this function.

SystemClock.sleep () is a function provided by android. InterruptedException does not occur during the call of this function, and the interrupt event will be delayed until the next interrupt event.

SystemClock.sleep (millis) is a utility function very similar to Thread.sleep (millis) , but ignores InterruptedException . Use this function for delays if you are not using Thread.interrupt () , since it will save the interrupted state of the thread.

Conclusion: If you want to hold the Android application, go to SystemClock.sleep (millis).

+2
source share

The truth is this:

Thread.sleep (n) can be interrupted in a call of type AsyncTask using asyncTask.cancel (true)

SystemClock.sleep (n) seems to ignore any aborted command, so there may be a risk of a memory leak when you use it similarly here: https://github.com/square/leakcanary/blob/master/leakcanary-sample/src/ main / java / com / example / leakcanary / MainActivity.java

0
source share

All Articles