如何根据 ArrayList 中的时间表一次打印一行?
How to printout a single line at time according to a schedule from an ArrayList?
我正在尝试创建一种一次打印一行的方法,中间有两分钟的延迟。我怎么做?。
这部分代码读取一个文本文件 (questionsFile) 并创建一个 ArrayList:
public Broadcaster(Socket connection) throws IOException {
read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
write = new PrintStream(connection.getOutputStream());
List<String> questionsList = new ArrayList<>();
try (Stream<String> questionsStream = Files.lines(Paths.get(questionsFile))) {
questionsList = questionsStream
.parallel()
.collect(Collectors.toList());
} catch (IOException w) {
w.printStackTrace();
}
下面有一个计时器,但出于某种原因,我无法让它工作。整个 ArrayList 被打印出来,没有任何延迟。我的意图是使用 printStream 但出于测试目的,文本当前已打印到控制台。如何重写代码使其一次打印一行?
List<String> finalQuestionsList = questionsList;
timer.schedule(task(() -> finalQuestionsList.forEach(System.out::println))
, 120, TimeUnit.SECONDS.toMillis(1));
}
private TimerTask task(Runnable task) {
return new TimerTask() {
@Override
public void run() {
task.run();
简单的解决方案是:
for (String question : questionsList) {
timer.schedule(task(() -> System.out.println(question)), 0);
try {
sleep(2000);
} catch (Exception ignored) {}
}
我正在尝试创建一种一次打印一行的方法,中间有两分钟的延迟。我怎么做?。
这部分代码读取一个文本文件 (questionsFile) 并创建一个 ArrayList:
public Broadcaster(Socket connection) throws IOException {
read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
write = new PrintStream(connection.getOutputStream());
List<String> questionsList = new ArrayList<>();
try (Stream<String> questionsStream = Files.lines(Paths.get(questionsFile))) {
questionsList = questionsStream
.parallel()
.collect(Collectors.toList());
} catch (IOException w) {
w.printStackTrace();
}
下面有一个计时器,但出于某种原因,我无法让它工作。整个 ArrayList 被打印出来,没有任何延迟。我的意图是使用 printStream 但出于测试目的,文本当前已打印到控制台。如何重写代码使其一次打印一行?
List<String> finalQuestionsList = questionsList;
timer.schedule(task(() -> finalQuestionsList.forEach(System.out::println))
, 120, TimeUnit.SECONDS.toMillis(1));
}
private TimerTask task(Runnable task) {
return new TimerTask() {
@Override
public void run() {
task.run();
简单的解决方案是:
for (String question : questionsList) {
timer.schedule(task(() -> System.out.println(question)), 0);
try {
sleep(2000);
} catch (Exception ignored) {}
}