简体   繁体   中英

How to multithread console output messages printing with other threads (Java)?

I am working on a program which contains a method which redirects the console output messages from the console to a JTextArea in a GUI. The program also uses a thread, which is responsible for acquiring some values from an external device and printing them in another GUI. The redirection method and this thread do not share any variables or objects. Here is a piece of the code:

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...
            }

    }

}

The method redirectSystemStreams() is called only once during the GUI's instantiation. After that, all the messages that would be printed to the console output should be printed in a JTextArea located in one of the GUI's.

The thread (from MyThread) must be synchronous (execute after every x seconds).

My current problem is the following: After some days, I noticed that the thread was preventing the JTextArea to print properly the messages that should come from the output console. When the thread does not run, the redirectSystemStreams() works fine.

I know that one of the problems may lie on the while(true) inside the thread's run() method, but I am still fresh on multithreading and I am really confused on what to do here. What should be the best solution here? If any additional code is needed, feel free to ask.

Create a separate thread to call redirectSystemStreams, not the main thread. And you might want to increase your sleepDelay to at least 1000.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM