Lesson 6 / 38
Threads & Runnable
Start threads with Runnable and start(), wait with join(), and see how Java 21 virtual threads make blocking code scale to millions of tasks.
Create and start
Pass a Runnable to a Thread and call start() (not run(), which would execute on the current thread). join() waits for it to finish. Prefer an executor over managing raw threads.
Thread t = new Thread(() -> {
System.out.println("worker: " + Thread.currentThread().getName());
});
t.start();
t.join();Virtual threads
Java 21 adds virtual threads — cheap, JVM-scheduled threads you can create by the million. Blocking IO on a virtual thread parks it without pinning an OS thread, so straightforward blocking code scales.