Confused with the theme template

This may sound like a very funny and silly question.

I am trying to view background activities using Runnables, Threads, Services and Intent Services in an android application.

So, I created an activity and created a simple flow inside the activity, for example

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 script, the button text changes.

It doesn't matter what I call:

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

      

OR

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

      

Why does my button text change when start () is called; - when is the background thread used?

Now for a very funny scenario; if I put a delay of 2 seconds, for example:

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 the view is not refreshed if I call start (); in run () calling case. It will work.

The difference between start () and run () is clear, but the question is the same why the button text is updated if the Thread is in the background.

+3


source to share


2 answers


First, your naming is not very good:

public class ExectuableThread implements Runnable {

      

would mean that instances of this class are streams, but of course they are not. So you are adding confusion to the whole problem right there.



My question is, why does the text of my button change when start () is called; The theme runs in the background.

The thing is, when you're not doing the "right way", especially in multithreading, all sorts of things are possible.

Meaning: You must use runOnUiThread to update UI elements in Android . Updating UI elements in other threads may or may not work.

+2


source


The main difference is that when you call the start () method of the calling method, a new Thread is created and the run () method is executed on the new thread, while if you call the run () method directly, the new Thread is not created, and the code inside run () will be execute on the current thread.



And the second difference is that you call start () method twice, then it will throw IllegalStateException

-1


source







All Articles