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

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.

解决方案

Here might be some sample code to fix the problem:

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();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值