26

I have read documents about Thread on Android, but I could not find differences between UI thread and Worker Thread. Can someone just give me more example about it?

Damia Fuentes
  • 5,308
  • 6
  • 33
  • 65
Quang Dai Ngo
  • 293
  • 1
  • 3
  • 8

2 Answers2

45

The Ui thread is the thread that makes any changes required for the ui.

A worker thread is just another thread where you can do processing that you dont want to interupt any changes happening on the ui thread

If you are doing large amounts of processing on the ui thread while a change to the ui is happening the ui will freeze until what ever you have running complete.

Stimsoni
  • 3,166
  • 2
  • 29
  • 22
  • 1
    @Stimsoni thank you sir, but can you tell me some real time example..When we have to use worker thread and when we have to use background thread – Gowthaman M Jul 01 '17 at 12:37
  • 1
    @GowthamanM. A worker thread and background thread are the same thing. so you would use a background/worker thread for anything that will take time to complete and is not updating the UI. A few examples, Accessing the database, an API Call, long sorting algorithms, image manipulation, parsing data (json -> pojo) etc. Does that help? – Stimsoni Jul 03 '17 at 04:38
21

It's partly terminology. People use the word "worker" when they mean a thread that does not own or interact with UI. Threads that do handle UI are called "UI" threads. Usually, your main (primary) thread will be the thread that owns and manages UI. And then you start one or more worker threads that do specific tasks. These worker threads do not modify the UI directly.

for example, if we need to change UI component like change text in Text View, show toast etc , show alert then we need to use UI thread bcoz thread is just process

we can access UI in thread using runOnUiThread method

example of runOnUiThread: use this method inside thread

new Thread() {
        @Override
        public void run() {
            //If there are stories, add them to the table
            try {
                     // code runs in a thread
                     YourActivity.this.runOnUiThread(new Runnable() {
                         @Override
                         public void run() {
                             Toast.makeText(context,"this is UI thread",0).show();
                         }
                    });
               } catch (final Exception ex) {
                   Log.i("---","Exception in thread");
               }
        }
 }.start();
Jenisha Makadiya
  • 832
  • 5
  • 17
  • 2
    can you tell me some real time example..When we have to use worker thread and when we have to use background thread.@Jenisha Makadiya – Gowthaman M Jul 01 '17 at 12:38