我已經改變了文字,所以一些評論可能會提到以前的版本如何處理一對相關的線程對象?
以下是代碼示例。有兩個線程:observer和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");
}
}
@John如何編碼不同?我想要丟棄物體。 – Dims 2012-09-10 15:22:11