示例
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 文档(Sun Microsystems 版权所有):
应该使用通过简单修改某个变量来表示目标线程应该结束运行的代码来代替许多使用 stop 的地方。
目标线程应该定期检查该变量,若该变量表示将要停止运行线程,将从它的 run 方法定期返回该变量。如果目标线程等待很长时间(例如,在条件变量中),应该使用 interrupt 方法中断等待。
使用提供的 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();
}