/* * Example of implementing a thread using Runnable interface */ public class Sleepy implements Runnable { protected Thread thread; protected String name; protected boolean interrupted; public Sleepy(String name) { this.name = name; interrupted = false; } /* * Implement Runnable interface */ @Override public void run() { while (!interrupted) { System.out.println(name + ": Sleeping"); try { Thread.sleep(1000); } catch(InterruptedException e) { interrupted = true; } System.out.println(name + ": Awake"); } } /* * Starts the thread */ public void start() { if (thread == null) { thread = new Thread(this, name); thread.start(); } } /* * Terminates the thread */ public void terminate() { thread.interrupt(); interrupted = true; // wait for the thread to terminate while (thread.isAlive()) { try { Thread.sleep(10); } catch (InterruptedException e) {} } System.out.println(name + ": stopped"); } }