Home » Android » java – What is the different between Handler, Runnable, and Threads?

java – What is the different between Handler, Runnable, and Threads?

Posted by: admin April 23, 2020 Leave a comment

Questions:

What is the difference between Handler, Runnable, and Threads?

While I was working with android, and I need something to run in the background. I use Threads to run it. Usually I would write a class that extends Thread and implement the run method.

I have also saw some examples that implments runnable and pass into runnable into Threads.

However I am still confused. Can someone give me a clear explanation?

  1. What is the point of Runnable if one can write the background code in the Thread’s run method?
  2. How is Handler used inside thread and why do we need to use it.
  3. Android has another thing call runOnUiThread, How do we use that? I know that it is used for updating the UI.
How to&Answers:

Why use Runnable over Thread?

  • Runnable separates code that needs to run asynchronously, from how the code is run. This keeps your code flexible. For instance, asynchronous code in a runnable can run on a threadpool, or a dedicated thread.

    A Thread has state your runnable probably doesn’t need access to. Having access to more state than necessary is poor design.

    Threads occupy a lot of memory. Creating a new thread for every small actions takes processing time to allocate and deallocate this memory.

What is runOnUiThread actually doing?

  • Android’s runOnUiThread queues a Runnable to execute on the UI thread. This is important because you should never update UI from multiple threads. runOnUiThread uses a Handler.

    Be aware if the UI thread’s queue is full, or the items needing execution are lengthy, it may be some time before your queued Runnable actually runs.

What is a Handler?

  • A handler allows you to post runnables to execute on a specific thread. Behind the scenes, runOnUi Thread queues your Runnable up with Android’s Ui Handler so your runnable can execute safely on the UI thread.

Answer:

1. Why runnable ?

Runnable is just an interface you need to instantiate a thread to contain it. Whereas thread already contains the ability to spawn a thread.If you extend Thread you can’t extend anything else (Java doesn’t support multiple inheritance). You can have multiple interfaces on a class, therefore you could have Runnable.

Also, When you extends Thread class, each of your thread creates unique object and associate with it. When you implements Runnable, it shares the same object to multiple threads.

2. Why to Use handler and what is it ?

Handler is written in Java (internally use a Thread), so everything you can do with Handler, you can achieve using a Thread too.

So why should you use Handler? Reason is as below

  • Handler allows you to send and process Message and Runnable objects
    associated with a thread’s MessageQueue. To put it in simple terms,
    handler makes your job easy.

  • Android has two main rules for handling threads:

  • Do not block the UI thread

  • Do not access the Android UI toolkit from outside the UI thread

To bind by the 2 rules stated above, In android we have 3 built-in methods that can handle the situation when one of your Activity classes are run on or called from a different thread.

We can then schedule the UI updates to be run on the UI thread with these three methods below. The Activity or View then works as a handler (more on handlers below) and schedules your runnable to the UI thread:

  1. Activity.runOnUiThread(Runnable)
    1. View.post(Runnable)
    2. View.postDelayed(Runnable, long) //(long = time to scheduling)

3. What is UI Thread ?

UI thread is the main thread in which the UI elements like View and Activity are rendered. Any time consuming operations should not happen in the UI Thread. The application default runs in UI Thread. You need not do anything special to use the UI Thread.

Answer:

Handler, Runnable, and Threads actually work together, I dont think you should compare them.

Handler

allows send messages between two threads in a safe manner, that means that sending thread puts message into destination thread queue, and this destination queue will process this message in its appropriate time.

Runnable

this is an interface that you implement, in implementation you put logic you want to execute on some thread. You can actually use Runnable also in non thread related places. Lots of Java apis actually use Runnable, not only Thread’s. You can post Runnable using handler, or you can use it with executors. Runnables are nice because you can implement them in a form of anonymous implementation.

UniThread

you meant UI Thread? Most user interfaces implements its workings in single thread, all UI elements: windows/widgets communicate using messages (just like in Handler). Ie. user presses button, this initiates a message with information that button was pressed, it is send to UI thread and finally delivered to your listener.

In Android it is forbidden (results in exception) to modify UI elements from non UI thread, this makes sense – if you would modify it from other thread this could happen while UI thread is doing some changes to the same widget – resulting in Undefined Behaviour.

Answer:

I use Threads to run it. Usually I would write a class that extends Thread and implement the run method.

1.What is the point of Runnable if one can write the background code in the Thread’s run method?

Using Runnable and creating a Thread from Runnable is general practice.

From oracle tutorial on concurrency regarding Runnable Vs Thread usage :

Runnable object, is more general, because the Runnable object can subclass a class other than Thread.

2.How is Handler used inside thread and why do we need to use it.

It’s a vast topic to explain. In simpler terms from official documentation site:

  1. Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue.

  2. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it — from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

  3. There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own

  4. When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create. You can create your own threads, and communicate back with the main application thread through a Handler. This is done by calling the same post or sendMessage methods as before, but from your new thread. The given Runnable or Message will then be scheduled in the Handler’s message queue and processed when appropriate.

This picture from blog.mindorks.com article by Anishar Ali explains concepts clearly.

enter image description here

3.Android has another thing call runOnUiThread, How do we use that? I know that it is used for updating the UI.

You can find more details by looking into implementation of runOnUiThread

/**
     * Runs the specified action on the UI thread. If the current thread is the UI
     * thread, then the action is executed immediately. If the current thread is
     * not the UI thread, the action is posted to the event queue of the UI thread.
     *
     * @param action the action to run on the UI thread
     */
    public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

Refer to below post for example code of Handler usage.

Android: Toast in a thread

Answer:

What is the point of Runnable if one can write the background code in
the Thread’s run method?

Runnable is an interface which used for creating a new thread class similar to the thread class created by extending java.lang.Thread class. Only difference is, Runnable interface allows the class to extend other class (if required) to override/inherit functionality of some class. Extending java.lang.Thread class will revoke this capability.

Also, Runnable interface represent a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is good design decision.

Read more: http://javarevisited.blogspot.com/2012/01/difference-thread-vs-runnable-interface.html#ixzz2qgjDYJhT

Answer:

Runnable Interface is parent of Thread Class and run() is method of Runnable Interface
So normally we should prefer Runnable interface over extending thread class because we don’t want to change behavior of the class and we can also extend another class .It also help in achieving loose coupling as well as we have a benefit of changing the User Interface from any other class.

We Can change Ui in 4 ways

1.By using Handler example

public class MainActivity extends AppCompatActivity {    
private Handler mainHandler=new Handler();
class ExampleRunnable implements Runnable {
        int seconds;

        public ExampleRunnable(int seconds) {
            this.seconds = seconds;
        }

        @Override
        public void run() {
            for (int i = 0; i < seconds; i++) {
 mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                        button.setText("50% process completed");
                        }
                    });

2.By Using runOnUIThread() we have to attach runOnUIThread with post it can be easily understood with example

class ExampleRunnable implements Runnable {
        int seconds;



 public ExampleRunnable(int seconds) {
        this.seconds = seconds;
    }

    @Override
    public void run() {runOnUIThread.post(new Runnable() {
                    @Override
                    public void run() {
                        button.setText(" Runnable");
                    }
                });
            }

3.By using any View we can call by any view here i have called with switch

public class MainActivity extends AppCompatActivity {
 private Switch aSwitch;
@Override
    protected void onCreate(Bundle savedInstanceState) {
 aSwitch=findViewById(R.id.switch1);
class ExampleRunnable implements Runnable {
            int seconds;



     public ExampleRunnable(int seconds) {
            this.seconds = seconds;
        }

        @Override
        public void run() { aSwitch.post(new Runnable() {
                        @Override
                        public void run() {
                            button.setText(" Runnable");
                        }
                    });
                }

4.By making Handler in another Thread we have to define Looper because by default it attach us to our thread looper

Handler threadHandler=new Handler(Looper.getMainLooper());
threadHandler.post(new Runnable()
{
                            @Override
                            public void run() {
                                button.setText(" Runnable");
                            }
                        });
                    }

This are 4 ways of implementing so I think from it you may now something about runnable thread and runOnUIThread() and Handler is written by other person beautifully.