Android from the foundation · Puzzle 2 of 16

Threads are the workers

Inside every process, the work is done by workers that run code one step at a time. One of them, in every app, is in charge of the screen.

The problem

In puzzle 1, the kernel handed the CPU to a process. But a process often needs to do several things at once: download a song, play it, and keep the screen responsive. Who actually runs the code inside a process?

See it

Inside an app's process, several threads work; the main thread at the front desk draws the screen and handles taps; while it is busy, a tap waits kernel one app's process threads download… the screen main thread slow task tap tap waitsfrozen
  1. Inside a process, the work is done by threads: workers that run code one step after another. A process can have several.

    Step 1 of 4
  2. One of them is special: the main thread, at the front desk. It draws the screen and handles taps, while other threads download or calculate in the back.

    Step 2 of 4
  3. A tap arrives, but the main thread is busy. Predict: can a worker from the back handle it?

    Step 3 of 4
  4. No: taps are the main thread's job. The kernel can give the CPU to other threads, but the tap still needs the main thread. The tap waits, and the screen seems frozen until the main thread is free.

    Step 4 of 4

The building block

A thread is a worker inside a process. It runs code one step after another. A process can have several threads, and the kernel gives each of them turns on the CPU, just as it does with processes.

Every Android app has one special thread: the main thread. It's the one that draws the screen and handles taps. Other threads can download or calculate, but anything on the screen is the main thread's job. (Why only one thread? Puzzle 14.)

The analogy

Inside the house work several people. One of them, the clerk at the front desk, deals with everything visitors see: that's the main thread. The others work in the back.

Check yourself

The main thread is busy for 3 seconds sorting a huge list. The user taps a button. What happens?

Not quite. Taps and drawing are the main thread's job only. Other threads can't step in.

Right. Only the main thread handles taps and drawing, so while it's busy, the screen waits.

Not quite. The kernel shares the CPU between threads, but it doesn't take over the main thread's work.

Why put a download on another thread, not the main thread?

Not quite. Any thread can download. The point is to keep the main thread free.

Right. The main thread must stay free for the screen.

What's the difference between a process and a thread?

Not quite. A process is the house; threads are the people working inside it. One process, many threads.

Right. Threads live inside a process and share its memory.

Sources

What you now know

A process can have many threads, but only one, the main thread, draws your screen and handles taps. If it's busy, the screen waits.