我知道 Java 的实际模型是用于协作线程的,并且它强制线程死亡是不可能发生的。
已弃用(出于Thread.stop()
上述原因)。我试图通过 BooleanProperty 侦听器停止线程。
这是MCVE:
TestStopMethod.java
package javatest;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ObservableValue;
public class TestStopMethod extends Thread {
private BooleanProperty amIdead = new SimpleBooleanProperty(false);
public void setDeath() {
this.amIdead.set(true);
}
@Override
public void run() {
amIdead.addListener((ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
System.out.println("I'm dead!!!");
throw new ThreadDeath();
});
for(;;);
}
}
看门狗.java
package javatest;
import java.util.TimerTask;
public class Watchdog extends TimerTask {
TestStopMethod watched;
public Watchdog(TestStopMethod target) {
watched = target;
}
@Override
public void run() {
watched.setDeath();
//watched.stop(); <- Works but this is exactly what I am trying to avoid
System.out.println("You're dead!");
}
}
驱动程序.java
package javatest;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Driver {
public static void main(String[] args) {
try {
TestStopMethod mythread = new TestStopMethod();
Timer t = new Timer();
Watchdog w = new Watchdog(mythread);
t.schedule(w, 1000);
mythread.start();
mythread.join();
t.cancel();
System.out.println("End of story");
} catch (InterruptedException ex) {
Logger.getLogger(Driver.class.getName()).log(Level.SEVERE, null, ex);
}
}
}