如何每5秒增加一次不会阻止我的UI的int? [重复]

问题描述 投票:-3回答:2

这个问题在这里已有答案:

我有阵列String[] announcement = new String[20];有20个值,我想每5秒检索一次。我找不到任何解决方案如何在不阻止我的UI的情况下每5秒进行一次增量。

java javafx javafx-8 javafx-2
2个回答
1
投票

你需要的是一个ThreadThreads与您的程序一起运行,以便您可以在程序仍然运行时运行冗长的任务(例如下载文件)而不会冻结。每隔五秒钟为你的字符串设置一个值的程序(这是我假设你从你的解释中做的那样)的例子如下所示:

import java.util.concurrent.TimeUnit;

class Main {
    public static void main(String[] args) {
            // Thread runs alongside program without freezing
            String[] retrievalArary = new String[20];
            Thread thread = new Thread(new Runnable() {
                public void run() {
                    for (int i = 0; i < retrievalArary.length; i++) { // Run for the same count as you have items in your array
                    try {
                        TimeUnit.SECONDS.sleep(5); // Sleeps the thread for five seconds
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                        retrievalArary[i] = Integer.toString(i); // Add the integer run count to the array
                        System.out.println(i); // Show progress
                    }

                }
            });
            thread.start();

    }
}

我无法确切地说出您要完成的任务,但您可以轻松地更改该代码以满足您的要求。


1
投票

由于问题是用JavaFX标记的,我假设你想在检索值后更新一些Node。如果使用普通线程实现,则必须使用Platform.runLater包装代码。但是如果你使用javafx.animation.Timeline,你不需要做额外的工作。

String[] announcement = new String[20];

AtomicInteger index = new AtomicInteger();

Timeline timeline= new Timeline(new KeyFrame(Duration.seconds(5), e->{
   String msg = announcement[index.getAndIncrement()];
   // Use this value to do some stuff on Nodes.
});
timeline.setCycleCount(announcement.length);
timeline.play();
© www.soinside.com 2019 - 2024. All rights reserved.