示例
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 方法返回。如果目标线程等待了很长时间(例如,等待某个条件变量成立),则应该使用中断方法来中断等待。
使用提供的 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();
}