範例
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 擷取而來(著作權為 Sun Microsystems 所有)
stop 的許多用法都應該取代為只修改某些變數來指出目標執行緒應該停止執行的程式碼。
目標執行緒應該定期檢查這個變數,如果變數指出它將停止執行,便循序從它的 run 方法返回。 如果目標執行緒等很久(例如,等待某個條件變數),便應該利用岔斷方法來岔斷等待。
請使用提供的 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();
}