What is Thread?

Let's know something about Thread!!!

Amandeep Singh
2 min readOct 17, 2023
Photo by amirali mirhashemian on Unsplash

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

  1. OS Thread
  2. User Thread

Thread can be created in two ways

  1. Extend the Thread Class
  2. 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

  1. Mutual Exclusion(Mutex) : object lock
  2. 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.

--

--

Amandeep Singh

👓 Software Engineer | 📚 Lifelong Learner | 🧩 Problem Solver | 🔧 Process Engineer | 🏗️ App Architect | ☕ Java Junkie