What is the difference between thread.sleep and systemclock.sleep. and which one should be used in AsyncTask?

I realized that if I exit the activity when I start AsyncTask in the middle, and when I try to start this action again, I will have to wait until the previous AsyncTask has finished before starting the new AsynTask. I tried both thread.sleep and systemclock.sleep and this gives me the same result. This makes sense because I think the thread that I closed and opened is the same. Is there a way to simply cancel AsyncTask if the user logs out of activity? Because, the second time the user enters the same activity, he will not have to wait until the previous one ends. I tried asyntask.cancel (true) in onPause (), it does not work, the same thing happened.

+4
source share
1 answer

As I understand it, the only difference between Thread.sleep () and SystemClock.sleep () is that Thread.sleep () can be interrupted. That is, something like:

SystemClock.sleep(10*1000); 

the calling thread sleeps for 10 seconds, and you just have to wait. Pay attention to:

 Thread.sleep(10*1000); 

the caller will also sleep for 10 seconds. But if you have a link to a sleeping thread from another thread, now you have the option:

 sleepingThread.interrupt(); 

which effectively wakes sleepThread from its 10 second sleep.

In the context of your question, which is best suited for AsyncTask, I think it still fully meets your requirements. Of course, I don’t know your exact code, but given your task, doInBackground seems to be sleeping a bit, and given that you want to cancel your task at any time, Thread.sleep () may make more sense.

+7
source

Source: https://habr.com/ru/post/1432597/


All Articles