Listing D
public class MyClass {

    boolean done = false;
    Object stoplight = new Object();

    public void stopLooper() {
        synchronized (stoplight) {
            done = true;
        }
    }

    public void startLooper() {
        (new Thread("looper") {
            public void run() {
                while (true) {
                    synchronized (stoplight) {
                       if (done) {
                            return;
                        }
                    }
                    // do something that takes a little while
                }
            }
        }).start();
    }
}