What is the difference between Runnable, Handler, Thread?
We also have the AsynkTask, sometimes we use them for certain things, but should we use each one in specific cases?
A Handler is made in Java (internally it uses a Thread), so everything you can do with Handler, can be achieved with a thread as well.
So why use Handler? The reason is as below:
Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. To put it simply, the handler makes your job easier.
Android has two main rules for handling threads:
Don't block the UI thread
Don't access the Android UI Toolkit from outside the UI thread
To link by the 2 rules indicated above, in android we have 3 built-in methods that can handle the situation when one of its activity classes is executed or called from a different thread.
We can then schedule the UI updates to run on the UI thread with these three methods below. The activity or view works as a handler (more about handlers below) and schedules its execution to the UI thread:
- Activity.runOnUiThread (Runnable)
- View.post (Runnable)
- View.postDelayed (Runnable, long) // (long = time until scheduling)
It allows sending messages between two threads in a safe way, this means that the sending thread puts the message on the destination thread queue and this destination queue will process this message at its appropriate time.
Runnable is just an interface that you need to instantiate a thread to contain it. Whereas the thread already contains the ability to generate a thread. If you extend the thread you cannot extend anything (Java does not support multiple inheritance). You can have multiple interfaces in a class, therefore you could have Runnable.
Also, when you extend the Thread class, each thread creates a unique object and associates itself with it. When you implement Runnable, you share the same object with multiple threads.
This is an interface to implement, in the implementation you put the logic you want to execute in some thread. You can also use Runnable in non-thread related places. A lot of Java apis actually use Runnable, not just Thread's. You can publish Runnable using the controller, or you can use it with the executors. Runnables are good because you can implement them in an anonymous implementation form.
Thread is a thread of execution in a program. The Java virtual machine allows an application to have multiple threads of execution running simultaneously.
Each thread has a priority. Threads with higher priority run in preference to threads with lower priority. Each thread may or may not be marked as a daemon. When code running on some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the create thread and is a daemon thread if and only if the create thread is a daemon.
When a Java virtual machine starts, there is usually a single non-daemon thread (which usually calls the method named
main of some designated class). The Java virtual machine continues to execute the threads until either of the following occurs:
exitmethod of the
Runtimeclass has been called and the security manager has allowed the exit operation to take place.
- All threads that are not daemon threads have died, either returning from the call to the run method or throwing an exception that is propagated beyond the
A Thread has a state that the runnable probably doesn't need to access. Having access to more states than necessary is poor design.
Threads take up a lot of memory. Creating a new thread for each small action requires processing time to allocate and deallocate this memory.
Most UIs implement their jobs in a single thread, all UI elements – windows / widgets communicate via messages (just like in Handler). That is to say. The user presses the button, it initiates a message with the information that the button was pressed, he is sent to the thread of the user interface and finally delivered to his listener.
On Android it is forbidden to modify UI elements from a non-UI thread, this makes sense. If you modify it from another thread, this could happen while the UI thread is making some changes to the same widget. . Google Translate for Business: Translator ToolkitWebsite TranslatorGlobal Market Finder About Google TranslateCommunityCellphones About GooglePrivacy & TermsHelpSend feedback
AsyncTask allows for proper and easy use of the UI thread. This class allows you to perform background operations and post results to the UI thread without having to manipulate threads and / or handlers.
AsyncTask is designed to be a helper class around Thread and Handler and is not a generic threading framework. AsyncTasks should ideally be used for short trades (a few seconds at the most). If you need to keep threads running for long periods of time, it is recommended to use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor, and FutureTask.
An asynchronous task is defined by a calculation that runs in a background thread and the result of which is published to the UI thread. An asynchronous task is defined by 3 generic types, named Params, Progress, and Result, and 4 steps, named onPreExecute, doInBackground, onProgressUpdate, and onPostExecute.
As a possibility, we can choose one over another:
- Use AsyncTask if you need to run a short task communicating with the UI thread
- Use a Thread and Handler to execute longer tasks that require communication between the working thread and the main thread (calling thread)
- Use Thread , Handler, and Looper (or HandlerThread , which is a class for starting a thread that already has a Looper) for longer tasks that require communication between the worker thread AND the caller's thread (not the main thread) .
- Use IntentService for a longer task that does not require user interaction and only needs one worker thread.