Search code examples
javaandroidmultithreadingthread-safetyrunnable

Confused with Thread Pattern


It may look a very funny and silly question..

I am trying to look around the Background operations with Runnables, Threads, Services and Intent Services in Android application.

So I created an activity and created a simple thread inside the activity like,

public class ExectuableThread implements Runnable{
  @Override
  public void run() {
    Log.e("current-thread", String.valueOf(Looper.getMainLooper().isCurrentThread())); // **Returning true**
    btnDone.setText("will not work");
  }
}

So in the above scenario button text is changing.

Doesn't matter I am calling like:

Thread t = new Thread (new ExectuableThread());
t.run();

OR

Thread t = new Thread (new ExectuableThread());
t.start();

Why My button text is changing if by calling start(); -when a background thread is used?

Now a very funny scenario; if I put a 2 sec delay, like this;

public class ExectuableThread implements Runnable{
  @Override
  public void run() {
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    Log.e("current-thread", String.valueOf(Looper.getMainLooper().isCurrentThread()));
    btnDone.setText("will not work");
  }
}

Then view is not getting updated if I call start(); in run() calling case. It will work.

Difference between start() and run() is clear but question is same why button text is updating if the Thread is in background.


Solution

  • First of all, your naming isn't too good:

    public class ExectuableThread implements Runnable {
    

    would imply that instances of this class are threads, but of course they aren't. So you are adding confusion to the whole issue right there.

    My question is Why My button text is changing if by calling start(); Thread runs in the background.

    Thing is: when you are not doing things the "right way", especially in multi-thread, all kinds of things can happen.

    Meaning: in order to update UI elements in Android, you should be using runOnUiThread. Updating UI elements within other threads might work, or might not work.