What is Thread?
Let's know something about Thread!!!
Definition of Thread
A Thread is a basic unit of CPU utilization. It is comprise of Registers, Programs, Counter, ThreadID and Stack
There are two types of Thread
- OS Thread
- User Thread
Thread can be created in two ways
- Extend the Thread Class
- Implement a Runnable and pass it to the Thread object
Runnable approach is better for thread use beacuse we can use other classes with our class as well
In Android when a response time takes more than 5 seconds or a braodcast that is unable to be finished within 10 seconds considered as ANR(Application Not Responding)
Thread Life Cycle
- New
- Runnable
- Blocked
- Waiting-> wait(), join(),park()
- Timed_Waiting->sleep(), wait(), join(),parknanos(),parkuntil()
- Terminated
Since Read and Write might occur at same time, this will result in corrupted data value being loaded. This situation is called a Race Condition.To avoid Race Condition we ca use different kind of synchronization tools, such as Semaphore and Mutex Lock.
Monitor
It is a thread-safe class, object, or module that wraps around a mutex in order to safely allow access to a method or variable by more than one thread
Monitor supports two kinds of thread Synchronization
- Mutual Exclusion(Mutex) : object lock
- Cooperative : wait and notify
Thread VS Runnable
Regular Thread and Handler Thread
The handler class can be used to register to a thread and provides a simple and secure channel to send data to this thread. The most obvious reason is communication between the caller thread and the worker Thread.
A handler allows you to communicate back with UI Thread from other background Threads. This is useful as Android doesn’t allow other Threads to communicate directly with UI Thread. A handler can send and process messages and runnable objects associated with a Thread message queue.
Thread is the parent of the handler. Handler internally uses Thread. You can use Thread for long-running background tasks without impacting UI Thread.