Exception Handling · Introduction to Java Programming

Terminating Threads

Watch lectures

Terminating Threads

1. How Threads Die (beginner)

Thread dies when run() ends (natural!) or flag says stop (polite!). NEVER stop() (deprecated — unsafe, locks break!). Like guest leaves after dinner (natural) or host signals (flag!).

2. Code — Flag Pattern (exam correct way!)

class Worker implements Runnable {
    volatile boolean running = true; // volatile (visible to all threads!)
    public void run() {
        while (running) { // check flag!
            System.out.println("working...");
            try { Thread.sleep(500); } catch (InterruptedException e) { break; }
        }
        System.out.println("cleaned + dead!");
    }
    void shutdown() { running = false; } // polite stop!
}
Worker w = new Worker();
Thread t = new Thread(w); t.start();
Thread.sleep(1500);
w.shutdown(); // ask stop (not force!)
t.join();     // wait till dead!

3. Methods (exam table!)

Method Job
run() ends natural death (best!)
flag running=false polite ask (preferred!)
interrupt() wake sleep/wait (handled via exception!)
join() waiter waits till thread dead!
stop() DEPRECATED (unsafe — never use!)

4. Traps

  • stop() kills mid-lock (corrupt data!) — banned in exams (write "deprecated"!).
  • volatile needed (else flag cached, thread never sees stop!).
  • Daemon threads die with main (setDaemon(true) before start()!).

5. Exam Points

  • Flag + join program — 5 marks, frequent.
  • Why stop() banned — 3 marks, favourite.
Free AppAndroid App

Coursify Android App

Generate AI courses, take quick quizzes between classes, and master complex engineering concepts on the go.

← All Introduction to Java Programming modules