範例

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();
}

解決方案
下列內容摘錄自 Java doc (copyright by Sun Microsystems)
許多出現 stop 的地方應該取代為只是修改一些變數的程式碼,表示目標執行緒應該停止執行。
目標執行緒應該定期檢查這個變數,如果變數指出要停止執行,則依序從執行方法中返回。如果目標執行緒等待太久(例如,在條件變數上),則應該利用中斷方法來中斷等待。
使用提供的 StopSafeRunnable。

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();
}