我有一个线程,它有一个名为terminate的布尔值 - 当它设置为true时,线程应该停止 - 问题是当我把它设置为false时它没有注册该线程?如何在我的线程中直接将terminate的值设置为true?感谢
btnPlayback.setOnMouseClicked(e -> {
Playback function = new Playback(list, progBar, settings);
Thread playback = new Thread(function);
if (recording == true) {
btnRecord.setText("Record");
recording = false;
}
if (playing == false) {
playing = true;
btnPlayback.setText("Stop");
playback.start();
} else {
playing = false;
btnPlayback.setText("Playback");
function.terminate();
}
});
这是在Thread的类
中 public void terminate() {
terminated = true;
}
应该阻止这样的陈述
for (InputValue i: list) {
if (terminated == false) {
答案 0 :(得分:0)
线程playback
负责在不同的线程上播放媒体(无论什么类型)。请在下次提供Minimal, Complete, and Verifiable example。
使用Thread的start方法启动playback-Thread。那是对的。但是你试着通过调用function.terminate()来阻止它。因为我不完全知道terminate()的上下文,所以我不能在这里帮助你,但更为一般。
更大的问题可能是,每次单击按钮时都会创建一个新的线程和一个新的回放对象。从以下代码来看,这似乎是错误的。
线程可以是interrupted
!所以你需要说一下线程,如果有人点击了“停止”按钮,就打断它的工作并完成线程。
将Thread和Playback变量移动到该块的外部。
在btnPlayback.setOnMouseClicked
方法中,在线程对象上执行以下操作:
playback.interrupt();
但是在你的Runnable Playback中,你必须注意中断。在你的Runnable中你需要一些证明标志中断状态的东西,比如:
if (Thread.interrupted()) {
throw new InterruptedException();
}
然后需要捕获异常并将终止设置为true。因为没有其他事可做,运行可以返回:
} catch (InterruptedException ex) {
terminate = true;
return;
}
可能的解决方案如下所示。但是我必须做出很多假设,因为你还没有全力以赴。也许您想要阅读更多的线程,然后访问本教程:https://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class JavaFXApplication8 extends Application {
Playback function = null;
Thread playback = null;
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setOnAction((ActionEvent event) -> {
if (function == null) {
function = new Playback(list, progBar, settings);
}
if (playback == null) {
playback = new Thread(function);
}
if (recording == true) {
btnRecord.setText("Record");
recording = false;
}
if (playing == false) {
playing = true;
btnPlayback.setText("Stop");
playback.start();
} else {
playing = false;
btnPlayback.setText("Playback");
playback.interrupt();
function = null;
playback = null;
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
static class Playback implements Runnable {
boolean terminate = false;
@Override
public void run() {
try {
// playing music or something else and ask sometimes, if this is interrupted
if (Thread.interrupted()) {
throw new InterruptedException();
}
} catch (InterruptedException ex) {
terminate = true;
return;
}
}
}
}