Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
860 views
in Technique[技术] by (71.8m points)

multithreading - Multiple threads using System.out.println in Java

I have a multi-threaded Java application that will output information about a message it receives to the console for debugging purposes. Each time the application receives a message, it will call a System.out.println(String) on the message.

The problem that I am having is that if the application gets flooded with messages, System.out.println() prints erroneous information (like old buffer information). This is leading me to wonder if there is a threading issue where multiple threads are calling the println function at one time, and not properly flushing the buffer.

In my main program (thread), I have something to the effect of:

while(iterator.hasNext())
{
    SelectionKey key = iterator.next();

    channel.receive(buffer);     // The buffer is a ByteBuffer.
    buffer.flip();

    new Thread(new ThreadToPrintTheMessage(buffer)).start();

    buffer.clear();

    iterator.remove();
}

In my thread, I have something to the effect of:

@Override
public void run()
{
    System.out.println(message);
    System.out.flush();   // I have better results with this.  But, it doesn't
                          // fully resolve the issue.
}

Is there a simple way for me to have multiple threads print out to the console at one time without the buffers containing old information?

Thanks

EDIT: updated the code in the main thread to be more representative of what my program is doing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
synchronized (System.out) {
    System.out.println(message);
    System.out.flush();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...