A Thread is a concurrent unit of execution. Thread is the light weight .The "Main." Thread is created when the execution for the application started. typically, there are several others for housekeeping. Multiple threads can exist within the same process and share memory resources. Execution of thread is fast compare to process.
Threads in the same Virtual Machine interact and synchronize by the use of shared objects and monitors associated with these objects. Synchronized methods and part of the API in Object also allow Threads to cooperate.
There are 2 way used the thread
- Create the own class that extends Thread and overriding run() method.
- The second think is implementation the Runnable interface.
dvantage of Multi Thread in Android
- Threads are execute independently, so speed of thread execution is fast compare to process.
- Threading provides an useful abstraction of concurrent execution.
- Multithreaded program utilizes more CPU resources and operates faster on computer systems that have multiple CPUs.
Interaction between Android threads is accomplished using Handler objects and posting Runnable objects to the main view.
Handler is used when secondary thread that wants to communicate with the main thread .It must request a message token using the obtainMessage() method.
The handleMessage() method is used to handle messages that arriving to the main thread.
There are two main uses for a Handler :
- Handler is used to schedule messages and runnables to be executed as some point in the future
- Handler is used to enqueue an action to be performed on another thread.
The post() method is helpful for A message extracted from the process’ queue.