在Java中使用System.out.println的多个线程

Pha*_*nto 6 java multithreading buffer println

我有一个多线程Java应用程序,它将收到的有关消息的信息输出到控制台以进行调试.每次应用程序收到消息时,它都会调用System.out.println(String)该消息.

我遇到的问题是,如果应用程序充满了消息,则会System.out.println()输出错误的信息(如旧的缓冲区信息).这让我想知道是否存在线程问题,其中多个线程一次调用该println函数,并且没有正确刷新缓冲区.

在我的主程序(线程)中,我有一些效果:

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();
}
Run Code Online (Sandbox Code Playgroud)

在我的帖子中,我有一些效果:

@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.
}
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法可以让多个线程一次打印到控制台而不包含包含旧信息的缓冲区?

谢谢

编辑:更新主线程中的代码,以更好地代表我的程序正在做什么.

Sam*_*erg 2

以下可能是一些解决该问题的示例代码:

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

    channel.receive(buffer);     // The buffer is a ByteBuffer.
    buffer.flip();
    byte[] bytes = new byte[buffer.limit()];  // copy buffer contents to an array
    buffer.get(bytes);
    // thread will convert byte array to String
    new Thread(new ThreadToPrintTheMessage(bytes)).start();

    buffer.clear();

    iterator.remove();
}
Run Code Online (Sandbox Code Playgroud)