Concurrency

concurrency1ThreadBasics

Path
pkg7concurrency/concurrency1ThreadBasics.java
Package
pkg7concurrency
Study order
1
Run
Single-file source launch
Command
java pkg7concurrency/concurrency1ThreadBasics.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg7concurrency/concurrency1ThreadBasics.java
1package pkg7concurrency;2 3/*4 * concurrency1ThreadBasics.java5 * -----------------6 * Creating threads (Runnable vs subclassing), start vs run, join, daemon threads.7 *8 * KEY POINTS:9 *   - Prefer implementing Runnable (composition) over extending Thread.10 *   - start() spawns a new thread; run() just calls the method on the current thread.11 *   - join() waits for a thread to finish.12 *   - Daemon threads don't keep the JVM alive.13 */14public class concurrency1ThreadBasics {15 16    public static void main(String[] args) throws InterruptedException {17        // 1) Runnable (preferred)18        Runnable task = () -> System.out.println("  running on: " + Thread.currentThread().getName());19        Thread t1 = new Thread(task, "worker-1");20        t1.start();21        t1.join();                         // wait for t1 to complete22 23        // 2) start() vs run()24        System.out.println("\nrun() executes on caller thread:");25        new Thread(task, "worker-2").run();    // NOTE: no new thread; runs on main26 27        // 3) Multiple threads and join all28        System.out.println("\nLaunching 3 threads:");29        Thread[] threads = new Thread[3];30        for (int i = 0; i < threads.length; i++) {31            int id = i;32            threads[i] = new Thread(() -> System.out.println("  thread " + id + " did work"));33            threads[i].start();34        }35        for (Thread t : threads) t.join();36 37        // 4) Daemon thread (background; won't block JVM shutdown)38        Thread daemon = new Thread(() -> {39            while (true) { try { Thread.sleep(100); } catch (InterruptedException e) { return; } }40        });41        daemon.setDaemon(true);42        daemon.start();43        System.out.println("\nDaemon alive: " + daemon.isAlive() + " (JVM can exit without waiting for it)");44 45        System.out.println("main thread finishing");46    }47}