1

我试图在一些延迟的情况下逐个字符地打印出一些文本,问题是它等待并等待,然后打印出整个句子。这就像它正在逐个字符地打印一个字符串,然后在完成后将该字符串打印出来:

public static void printWithDelay(String data, TimeUnit unit, long delay) 
  throws InterruptedException {
    for (char ch : data.toCharArray()) {
        System.out.print(ch);
        unit.sleep(delay);
    }
}

请帮忙 (:

4

3 回答 3

1

你为什么不使用Thread.sleep()

import java.lang.*;

public class PrintWithDelayExample {
    public static void main(String[]args) {
        printWithDelay("Hello! World", 500);
    }

    public static void printWithDelay(String data, long delay) {
        for (char c : data.toCharArray()) {
            try {
                Thread.sleep(delay);
                System.out.print(c);
            } catch (InterruptedException e) {}
        }
        System.out.println();
    }
}

请参阅使用睡眠暂停执行

以及如何正确使用线程睡眠

于 2015-10-08T15:38:51.710 回答
0

你用什么价值观来运行这个?如果您使用的睡眠值太小,因为您将所有内容都打印在一行上,它可能看起来像是一次全部写入。

尝试使用这些值运行它以夸大睡眠时间。您也可以尝试使用 aSystem.out.println而不是System.out.print向您展示它实际上是一次打印一个。

    try {
        printWithDelay("Some Text", TimeUnit.SECONDS, 5L);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
于 2015-10-08T15:15:17.980 回答
0

您可能会发现呼叫flush()会起作用,但不能保证。

public static void printWithDelay(String data, TimeUnit unit, long delay)
        throws InterruptedException {
    for (char ch : data.toCharArray()) {
        System.out.print(ch);
        // Add this.
        System.out.flush();
        unit.sleep(delay);
    }
}

冲洗()

刷新此输出流并强制写出任何缓冲的输出字节。flush 的一般约定是,调用它表示,如果先前写入的任何字节已被输出流的实现缓冲,则应立即将这些字节写入其预期目的地

于 2015-10-08T14:57:34.243 回答