-3

I have Array String[] announcement = new String[20]; that has 20 value, I want to retrieve each of them every 5 seconds. I can't find any solution how to make increment every 5 Seconds without blocking my UI.

John Smith
  • 21
  • 5
  • What do you mean by *retrieve*? Why not just use `Arrays#copyOf` on the array and then use the copy on some other thread every 5 seconds? – Jacob G. Mar 06 '19 at 18:25

2 Answers2

1

What you need is a Thread. Threads run alongside your program so that you can run lengthy tasks (such as downloading a file) while your program still runs without freezing up. An example of a program to set a value for your strings (which is what I assume you're doing from your explanation) every five seconds would look like this:

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();

    }
}

I couldn't really tell exactly what you were trying to accomplish, but you can change that code pretty easily to fit your requirements.

CyanCoding
  • 1,012
  • 1
  • 12
  • 35
  • A better solution would be to use a `ScheduledExecutorService`. See https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html – Christopher Schneider Mar 06 '19 at 18:52
1

As the question is tagged with JavaFX I assume you want to update some Node once your retrieve the value. If you use normal thread implementation, you have to wrap your code with Platform.runLater. But if you use javafx.animation.Timeline you dont need to do that extra work.

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();
Sai Dandem
  • 8,229
  • 11
  • 26