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 a process, the work is done by threads: workers that run code one step after another. A process can have several.
Step 1 of 4One 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 4A tap arrives, but the main thread is busy. Predict: can a worker from the back handle it?
Step 3 of 4No: 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
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.
Answer every question above correctly to unlock the next puzzle.