1

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.

earthw0rmjim
  • 19,027
  • 9
  • 49
  • 63

3 Answers3

3

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

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

earthw0rmjim
  • 19,027
  • 9
  • 49
  • 63
1

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.

Larry Schiefer
  • 15,687
  • 2
  • 27
  • 33
1

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.

orip
  • 73,323
  • 21
  • 116
  • 148
  • So, it's more likely to be "tasks execution order" rather than "handlers execution order"? – Plain_Dude_Sleeping_Alone Sep 07 '16 at 11:35
  • 1
    Think of handlers as a way to communicate between threads. The toast can only be displayed from the "Main" or "UI" thread. On of the ways of asking the main thread to run some code is via a handler. So the code will ask the main thread to toast "in the middle" before it asks it to toast "is completed". Technically, if the main thread is blocked, it may wait until it runs these requests, but in any case it'll process them in the order they're received. – orip Sep 07 '16 at 12:06
  • Okay I get it, basically the tasks come from the same thread so the sequence still matter. – Plain_Dude_Sleeping_Alone Sep 07 '16 at 12:11