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