Eksempel

public static final Boolean lock = Boolean.TRUE;

public static void main( String[] args ) {
Runnable runnable = new Runnable() {
public void run() {
synchronized ( lock ) {
while ( true ) {
System.out.println( "Hello World!" ); //$NON-NLS-1$
try { wait( 1000 ); } catch (InterruptedException e) {}
}
}
}
};
Thread thread = new Thread( runnable );
thread.start();
try { Thread.sleep( 3000 ); } catch (InterruptedException e) {}
thread.stop();
}

Løsning
Følgende er et uddrag af Java-doc (Copyright Sun Microsystems)
Mange anvendelser af Stop bør erstattes af kode, der simpelthen ændrer visse variabler for at angive, at udførelsen af målprogramdelen skal ophøre.
Målprogramdelen skal kontrollere variablen med regelmæssige mellemrum og melde korrekt tilbage fra udførelsesmetoden, hvis variablen angiver, at udførelsen skal stoppe. Hvis målprogramdelen venter i lange perioder (f.eks. på en betingelsesvariabel), bruges interrupt-metoden til at afbryde ventetiden.
Brug StopSafeRunnable, der er stillet til rådighed.

public static abstract class StopSafeRunnable implements Runnable {
public final void run() {
while ( !stopped ) {
doRun();
}
}
public void stop() {
stopped = true;
}
public boolean isStopped() {
return stopped;
}
protected abstract void doRun();

private boolean stopped = false;
}

public static void main(String[] args) {
StopSafeRunnable runnable = new StopSafeRunnable() {
public void doRun() {
System.out.println( "Hello World" ); //$NON-NLS-1$
try { Thread.sleep( 1000 ); } catch (InterruptedException e) {}
}
};
Thread thread = new Thread( runnable );
thread.start();
try { Thread.sleep( 3000 ); } catch (InterruptedException e) {}
runnable.stop();
}