/* * Example of implementing threads by extending the Thread class */ public class Sleepy extends Thread { protected String name; protected boolean interrupted; public Sleepy(String name) { this.name = name; interrupted = false; } /* * Override run() method of Thread class */ @Override public void run() { while (!interrupted) { System.out.println(name + ": Sleeping"); try { Thread.sleep(1000); } catch(InterruptedException e) { interrupted = true; System.out.println(name + ": interrupted"); } System.out.println(name + ": Awake"); } } /* * Terminates the thread */ public void terminate() { interrupt(); interrupted = true; // wait for the thread to terminate while (isAlive()) { try { Thread.sleep(10); } catch (InterruptedException e) {} } System.out.println(name + ": stopped"); } }