后台线程可以保持忙碌等待。这意味着您可以创建一个
CompletableFuture,用于
Platform.runLater创建警报并使用showAndWait将其显示,然后用结果填充未来。在后台线程上的此调用之后,使用来等待结果
Future.get。
以下示例生成0到9(含)之间的随机数,并在上打印0-8
textarea。
9是模拟错误,并且询问用户是否应该继续执行任务。
@Overridepublic void start(Stage stage) throws IOException { textarea ta = new textarea(); Thread thread = new Thread(() -> { Random rand = new Random(); while (true) { int i = rand.nextInt(10); if (i == 9) { CompletableFuture<ButtonType> future = new CompletableFuture<>(); // ask for user input Platform.runLater(() -> { alert alert = new alert(alertType./confirm/iATION); alert.setContentText("An error occured. Continue?"); future.complete(alert.showAndWait().orElse(ButtonType.CANCEL)); // publish result }); try { if (future.get() == ButtonType.CANCEL) { // wait for user input on background thread break; } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); break; } } else { Platform.runLater(() ->ta.appendText(Integer.toString(i) + "n")); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); break; } } } }); thread.setDaemon(true); thread.start(); Scene scene = new Scene(new VBox(ta)); stage.setScene(scene); stage.show();}


