我已经更改了文本,所以一些评论可能参考以前的版本
下面是代码示例。有两个线程:observer 和 observable。Observable 由 main 启动。观察者由可观察对象的创建开始,并以它的销毁结束。但它不会发生,观察者会永远运行。为什么?
public class ThreadObjectReaping01 {
private static final Logger log = LoggerFactory.getLogger(ThreadObjectReaping01.class);
public static void main(String[] args) throws InterruptedException {
Thread observable = new Thread("observable") {
private Thread observable2 = this;
Thread observer = new Thread("observer") {
@Override
public void run() {
log.info("Observer is starting");
while(!interrupted()) {
if( observable2.isAlive() ) {
log.info("Observable is running");
}
else {
log.info("Observable is NOT running");
}
try {
sleep(1000);
} catch (InterruptedException e) {
interrupt();
}
}
log.info("Observer is terminating");
}
};
{
observer.start();
}
@Override
protected void finalize() throws Throwable {
observer.interrupt();
}
@Override
public void run() {
log.info("Observable is starting");
while(!interrupted()) {
try {
sleep(1000);
} catch (InterruptedException e) {
interrupt();
}
//log.info("Observable is running");
}
}
};
log.info("Main is starting observable");
observable.start();
Thread.sleep(10000);
log.info("Main is interrupting observable");
observable.interrupt();
observable = null;
Thread.sleep(10000);
log.info("Main is terminating");
}
}