0

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(;;);
    }
}

WatchDog.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!");
    }

}

Driver.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);
        }

    }
}
4

1 に答える 1