gpt4 book ai didi

JAVAFX : Thread Stop/Start

转载 作者:行者123 更新时间:2023-12-02 02:17:56 24 4
gpt4 key购买 nike

我的应用程序当前正在连接到 Web 服务以获取在应用程序中使用的数据。我正在尝试对这个过程进行线程化,以便 getWebServiceData() 方法每 X 秒触发一次。我认为我的问题是我正在尝试使用相同的 WebServiceConnect 实例重新启动新线程,但我想不出任何其他方法......任何人都可以帮助我构造这个,以便复选框可以终止线程,然后在重新勾选时创建一个新的?

我可以轻松启动线程,一旦终止它就会重新启动它。我正在尝试使用复选框来实现此目的:

WebServiceConnect 类:

public class WebServiceConnect extends Thread {

private Boolean runThread = true;

public Boolean getRunThread() {
return runThread;
}

public void setRunThread(Boolean runThread) {
this.runThread = runThread;
}

//the run method comes from the thread class.
//allows code to be ran in the background.
public void run() {
System.out.println("Starting web service thread......");
try {
Thread.sleep(6000);
while(runThread) {
getWebServiceData();
System.out.println("The data has been refreshed.");
}
} catch (InterruptedException ex) {
Logger.getLogger(WebServiceConnect.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("terminating thread.....");
return;
} catch (IOException ex) {
Logger.getLogger(WebServiceConnect.class.getName()).log(Level.SEVERE, null, ex);
}

}

主类:

public class CourseworkThree extends Application {

private static final List<String> strings = Arrays.asList("2011", "2012", "2013");
private BarChart BarChart1;
private CheckBox[] checkBoxesYear;
WebServiceConnect wsc = new WebServiceConnect();

@Override
public void start(Stage primaryStage) throws IOException {
wsc.start();

HBox HBox1 = new HBox();
HBox1.setPadding(new Insets(10, 10, 10, 10));
HBox1.setSpacing(10);

//A checkbox with a string caption
CheckBox cb2 = new CheckBox("Refresh Data?");
cb2.setSelected(true);
HBox1.getChildren().add(cb2);

cb2.setOnAction((event) -> {
if(!cb2.isSelected()) {
wsc.setRunThread(false);
wsc.interrupt();
System.out.println("You have stopped refreshing data automatically.");
} else {
wsc.setRunThread(true);
wsc.start();

}
});

最佳答案

Java FX 提供了处理此类事情的服务。

例如。

private class KeepSessionAliveService extends ScheduledService<Void> {
@Override
protected Task<Void> createTask() {
return new Task<Void>() {
@Override
protected Void call() throws WhatEverException {
//Call your code.
return null;
}
};
}
}

然后设置您的时间。

private void startPolling() {
service = new KeepSessionAliveService() ;
service.setPeriod(Duration.minutes(6));
service.setDelay(Duration.minutes(6)); //If you want to wait before starting it.

service.setOnSucceeded(event -> Platform.runLater(() -> {
//reset back to FX Thread??
}));

service.start();
}

这将安排您的线程按预定义的时间间隔运行。它将在 FX 线程上运行,因此不会影响您的 UI。如果您关闭应用程序,服务将自行关闭。我在我的应用程序中使用它来保持与服务器的 session 处于 Activity 状态 - 就像一个魅力。

关于JAVAFX : Thread Stop/Start,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49011685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com