Reputation: 1889
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.
Upvotes: 1
Views: 1899
Reputation: 19427
My question is that whether it's true that the second handler will be executed last just after the first handler finishes its job.
A Handler
instance is associated to a single Thread
(also called a message queue).
Runnable
s are executed on this Thread
sequentially.
Calling post()
will put the Runnable
at the end of that queue, so yes, the second Runnable
will be executed after the first one.
Upvotes: 3
Reputation: 75577
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.
Upvotes: 2
Reputation: 15775
There are not two handlers in play, just a single handler on the UI thread (mUiHandler
). Your secondary thread is creating Runnable
objects and posting them to the Handler
. They will be executed by the handler in the order they are posted. Since the loop of the thread executes and posts first then the thread finishes by posting the "second" Runnable
, that second one will always execute last, relative to the other things posted within the loop.
Upvotes: 1