Explore four interactive simulations: Timer, Download Manager, Restaurant Kitchen and API Dashboard.
Three independent timers need to finish. Compare waiting for each timer one-by-one with letting their waiting periods overlap.
import threadingimport timedef timer(name, seconds): print(f"{name}: START") time.sleep(seconds) print(f"{name}: DONE")threads = [ Thread(target=timer, args=("A", 4)), Thread(target=timer, args=("B", 3)), Thread(target=timer, args=("C", 2))]for t in threads: t.start()for t in threads: t.join()
Files spend much of their lifetime waiting for network data. Start all downloads and observe that each progresses independently.
import threadingimport timedef download(file_name): print(file_name, "START") # waiting for network chunks... time.sleep(1) print(file_name, "DONE")threads = [Thread(target=download, args=(f,)) for f in files]for t in threads: t.start()for t in threads: t.join()
A cook does not stare at boiling pasta while another order waits. The cook can switch to useful work while an order is waiting.
Prep โ Boil โ Plate
Prep โ Grill โ Plate
Prep โ Mix โ Serve
import threadingimport timedef cook(order): print(order, "PREP") time.sleep(1) # waiting phase print(order, "RESUME") print(order, "DONE")# Concept mapping:# RUNNING -> WAITING -> RUNNING -> DONE
A dashboard needs three independent services. Launch requests together, then wait until every result is available before rendering the final screen.
import threadingt1 = Thread(target=load_profile)t2 = Thread(target=load_orders)t3 = Thread(target=load_payment)t1.start(); t2.start(); t3.start()t1.join(); t2.join(); t3.join()print("DASHBOARD READY")