我在 JavaFX 中使用一个线程在一定时间间隔(最初为 1 秒)后重复我的代码,但我希望能够根据用户选择将线程使用的时间间隔更改为 500 毫秒或 333 毫秒(我有一个按钮在菜单栏中更改每个选项)。如果用户单击其中一个按钮并使用新值再次启动它,我确实尝试了 shutdown() 之类的操作,但没有成功。有什么想法吗?
这是我的代码的相关部分:
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(() -> {
//refresh users, line and "guiche"
updateFila(usuarios, guiches, fila);
updateGuiche(guiches, fila, graphicsContext);
turno++;
//ends the code after the end of the line
if (done) {
exec.shutdown();
}
}, 0, 1000, TimeUnit.MILLISECONDS); //This is interval that I need to change after user choice
我知道我现在正在执行 scheduleAtFixedRate(),但这只是为了看看逻辑是否正确。
此外,我需要暂停、恢复和重置线程,所有这些都基于用户点击。
最佳答案
您可以使用时间轴每秒执行一个事件处理程序,并将动画运行的速率设置为每秒更新的次数,即 2 或 3...
在下面的示例中,我使用 5 而不是 3 以获得更容易识别的效果:
@Override
public void start(Stage primaryStage) {
Line line = new Line(25, 125, 125, 125);
Rotate rotate = new Rotate(0, 125, 125);
line.getTransforms().add(rotate);
ToggleButton btn = new ToggleButton();
btn.textProperty().bind(Bindings.when(btn.selectedProperty()).then("5 Hz").otherwise("2 Hz"));
StackPane.setAlignment(btn, Pos.BOTTOM_LEFT);
// rotate by one 60th of a full rotation each time
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), evt -> rotate.setAngle((rotate.getAngle() + (360d / 60d)) % 360)));
timeline.setCycleCount(Animation.INDEFINITE);
// rate depends on button state
timeline.rateProperty().bind(Bindings.when(btn.selectedProperty()).then(5d).otherwise(2d));
Pane linePane = new Pane(line);
linePane.setMinSize(250, 250);
linePane.setMaxSize(250, 250);
StackPane root = new StackPane();
root.getChildren().addAll(linePane, btn);
Scene scene = new Scene(root, 300, 300);
primaryStage.setScene(scene);
timeline.play();
primaryStage.show();
}
绑定(bind)只是设置更新频率的一个示例。您当然可以使用不同的方式来分配该值,例如
ComboBox<Duration> combo = new ComboBox<>();
Duration initial = Duration.seconds(1);
combo.getItems().addAll(initial, Duration.seconds(1/3d), Duration.seconds(1/2d));
combo.setValue(initial);
combo.valueProperty().addListener((observable, oldValue, newValue) -> timeline.setRate(1/newValue.toSeconds()));
关于java - 如何在可以更改的时间间隔后重复运行某些代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42732049/