Hey-men-whatsup Hey-men-whatsup - 2 months ago 13
Android Question

Matter of handlers execution in a sequence

I took this snipet from a site explaining handler in Android (a threading thing).

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Thread myThread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 4; i++) {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (i == 2) {

mUiHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MyActivity.this, "I am at the middle of background task",
Toast.LENGTH_LONG)
.show();
}
});
}
}//ends for()

// THE SECOND HANDLER, RIGHT HERE!
mUiHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MyActivity.this,
"Background task is completed",
Toast.LENGTH_LONG)
.show();
}
});
} //ends run()
});
myThread.start();


Judging from the task outputted in the second executed handler, which is

Toast.makeText(MyActivity.this,
"Background task is completed",
Toast.LENGTH_LONG)
.show();


Seems like the writer of the article is pretty much sure that the second handler will be executed last.

My question is that whether it's true that the second handler will be executed last just after the first handler finishes its job. Though, when I ran it multiple times, yes, it's executed last. In my mind, since the handler is done in the background thread then we're not supposed to know (even predict) which one the those two tasks the handler will execute first. I need an explanation, thank you in advance.

Answer

The outermost anonymous Runnable, the one passed to the new Thread(...) constructor, is what runs in the background thread. Everything inside that runnable will execute sequentially - one instruction after the other.

Since that runnable has a for loop and only after that the final toast appears you're guaranteed it'll run after the loop body.

Comments