0

有人告诉我,通过输出流输出的任何数据(在我的情况下我使用的是 tcp/ip)可能会阻塞。在这种情况下,我不想通过等待数据出去来停止应用程序。

我需要一个如何做到这一点的模型。

我需要通过这个流发送消息对象。

我在想我需要一个包含这些消息对象的阻塞队列。线程的 run() 方法将抓取任何可用的消息对象并发送它们,虽然是真的。

我的问题是

  1. 有没有比 while true 循环更好的方法来做到这一点?也许在 while true 循环中,如果没有要发送的消息,我可以告诉线程让 / 休眠。

  2. 有没有更好的模型可以使用?我担心如果我的代码中有一段时间(true),它会占用等待消息的处理器周期。

请有这方面经验的人告诉我是否有更好的方法。

谢谢,jbu

4

2 回答 2

0

Java has implemented two ways of doing this: by blocking methods (which you have already addressed) or by non-blocking methods.

For the easiest way to get to asynchronous communication by blocking methods you can take a look at this answer: question 1041014

If you want to use non-blocking methods, you have to take a look at the NIO framework. It is not particularly easy to implement in the beggining because it uses several complicated concepts, but once you get to understand how to handle the communication events it is pretty simple to make powerfull implementations. At the end you will end up using blocking methods because the CPU time is unnecesary to waste, but the NIO framework will let you create a single thread communication implementation which will be very optimal for cpu and memory usages.

Take a look at the O'reilly NIO book.

于 2009-07-07T01:39:59.820 回答
0

这是一个很好的机制,只要你的队列是阻塞的。在等待另一条消息到达队列时,您将自动让出处理器。

如果您以非阻塞方式读取队列,那么您将浪费大量 CPU 时间。您通常必须更加努力地做到这一点,但这完全取决于您使用的队列类型。

于 2009-07-06T23:44:09.163 回答