杀死属性侦听器中的线程(JavaFX 8)

时间:2014-10-08 17:45:04

标签: java multithreading javafx javafx-8 preemptive

我知道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);
        }

    }
}

1 个答案:

答案 0 :(得分:1)

如果更改属性值,则会在更改属性的同一线程上调用侦听器(只需考虑如何/可以实现属性类)。因此,在您的示例中,从支持ThreadDeath实例的线程抛出Timer错误,这实际上不是您想要的。

在外部(到该线程)终止线程的正确方法是设置一个标志,然后在线程的实现中定期轮询该标志。这实际上比听起来更棘手,因为必须从多个线程访问该标志,因此必须正确地同步对它的访问。

幸运的是,有一些实用程序类可以帮助解决这个问题。例如,FutureTask包含RunnableCallable并提供cancel()isCancelled()方法。如果您使用的是JavaFX,那么javafx.concurrent API提供了CallableRunnable的一些实现,并且还提供了专门用于在FX Application Thread上执行代码的功能。有些例子,请查看documentation for javafx.concurrent.Task

所以,例如,你可以这样做:

package javatest;
public class TestStopMethod implements Runnable {

    @Override
    public void run() {
        try {
            synchronized(this) {
                for(;;) {
                    wait(1); 
                }
            }
        } catch (InterruptedException exc) {
            System.out.println("Interrupted");
        }
    }
}

Watchdog.java:

package javatest;

import java.util.TimerTask;
import java.util.concurrent.Future;

public class Watchdog extends TimerTask {
    Future<Void> watched;
    public Watchdog(Future<Void> target) {
        watched = target;
    }
    @Override
    public void run() {
        watched.cancel(true);
        //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.concurrent.FutureTask;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Driver {

    public static void main(String[] args) {
        try {
            FutureTask<Void> myTask = new FutureTask<>(new TestStopMethod(), null);
            Timer t = new Timer();
            Watchdog w = new Watchdog(myTask);
            t.schedule(w, 1000);
            Thread mythread = new Thread(myTask);
            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);
        }

    }
}

在JavaFX应用程序中,您可能会这样做。请注意,如果您在没有运行FX应用程序线程的情况下尝试执行此操作,则会出现问题,因为必须在该线程上更新FX cancelled中的Task标志。

package javatest;

import javafx.concurrent.Task;

public class TestStopMethod extends Task<Void> {

    @Override
    public Void call() {
        System.out.println("Calling");
        while (true) {
            if (isCancelled()) {
                System.out.println("Cancelled");
                break ;
            }
        }
        System.out.println("Exiting");
        return null ;
    }
}

Watchdog.java:

package javatest;

import java.util.TimerTask;

import javafx.concurrent.Task;

public class Watchdog extends TimerTask {
    Task<Void> watched;
    public Watchdog(Task<Void> target) {
        watched = target;
    }
    @Override
    public void run() {
        watched.cancel();
        //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.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.concurrent.Worker;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class Driver extends Application {

    @Override
    public void start(Stage primaryStage) {
        try {

            TextArea console = new TextArea();
            BorderPane root = new BorderPane(console);
            Scene scene = new Scene(root, 600, 400);
            primaryStage.setScene(scene);
            primaryStage.show();

            Task<Void> myTask = new TestStopMethod();
            Timer t = new Timer();
            Watchdog w = new Watchdog(myTask);
            t.schedule(w, 1000);
            Thread mythread = new Thread(myTask);
            mythread.setDaemon(true);

            myTask.stateProperty().addListener((obs, oldState, newState) -> {
                console.appendText("State change "+oldState+" -> "+newState+"\n");
                if (oldState == Worker.State.RUNNING) {
                    t.cancel();
                    console.appendText("End of Story\n");
                }
            });
            mythread.start();

        } catch (Exception ex) {
            Logger.getLogger(Driver.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}