【问题标题】:How to multithread console output messages printing with other threads (Java)?如何使用其他线程(Java)打印多线程控制台输出消息?
【发布时间】:2014-08-28 12:34:54
【问题描述】:

我正在开发一个程序,该程序包含一个方法,该方法将控制台输出消息从控制台重定向到 GUI 中的 JTextArea。该程序还使用了一个线程,该线程负责从外部设备获取一些值并将它们打印到另一个 GUI 中。重定向方法和这个线程不共享任何变量或对象。这是一段代码:

private JTextArea outputText;

private void redirectSystemStreams() {
    OutputStream out = new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            updateTextArea(String.valueOf((char) b));
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            updateTextArea(new String(b, off, len));
        }

        @Override
        public void write(byte[] b) throws IOException {
            write(b, 0, b.length);
        }
    };

    System.setOut(new PrintStream(out, true));
    System.setErr(new PrintStream(out, true));
}

private void updateTextArea(final String text) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            outputText.append(text);
        }
    });
}

public class MyThread implements Runnable {

    private static final int sleepDelay         = 100;

    public MyThread() {}


    @Override
    public void run() {
        try {
            //do something...
            while(true) {
                Thread.sleep(MyThread.sleepDelay);
                //do something...
            }


        } catch(Exception e) {
                //do something...
            }

    }

}

方法redirectSystemStreams() 在GUI 的实例化过程中只被调用一次。之后,将打印到控制台输出的所有消息都应打印在位于其中一个 GUI 中的 JTextArea 中。

线程(来自 MyThread)必须是同步的(每 x 秒执行一次)。

我当前的问题如下:几天后,我注意到线程阻止JTextArea 正确打印应该来自输出控制台的消息。当线程不运行时,redirectSystemStreams() 工作正常。

我知道其中一个问题可能在于线程的run() 方法中的while(true),但我对多线程仍然很陌生,我真的很困惑在这里做什么。 这里最好的解决方案应该是什么?如果需要任何其他代码,请随时询问。

【问题讨论】:

  • 您是如何注意到 MyThread “阻塞”了控制台输出的?此外,100 毫秒是一个非常短的延迟。 MyThread 可能正在耗尽所有可用的 cpu 时间。
  • 我注意到了这一点,因为当我评论线程执行 ( myThread.run() ) 时一切正常。我将更改线程延迟并检查它是否有效...
  • 我不完全理解您的问题,但您可以从将 try-catch 语句移入 while(true) 循环开始。
  • 我只是做了一些测试,延迟值不是问题
  • 其他线程在做什么?

标签: java multithreading


【解决方案1】:

创建一个单独的线程来调用redirectSystemStreams,而不是主线程。您可能希望将 sleepDelay 增加到至少 1000。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 2011-07-26
    • 1970-01-01
    • 2011-01-05
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    相关资源
    最近更新 更多