我如何使用线程在java中模拟非阻塞i/o
我正在编写一次涉及服务器和许多客户端的简单应用程序。我必须使用 DataGramSocket。应用程序是通过控制台简单地交换消息,就像聊天一样。但是 in.readLine() 和 ds.receive() 中的操作都是阻塞的,将它们放在单独的线程中并没有帮助,因为阻塞 i/o 也会阻塞线程。谁能告诉我如果没有 nio 我该如何做到这一点
i m writing simple application involving a server and many clients at time. i have to use DataGramSocket. application is simple exchange of messages through console like in chatting. but both operations in.readLine() and ds.receive() are blocking and putting them in seperate threads didn't help as blocking i/o will block the thread too. can any body tell me how can i do that without nio
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您有专门用于通过网络发送或接收数据的线程,那么线程阻塞不会成为问题,因为只有该专用线程才会被阻塞。
然后,让我们考虑一下该解决方案对应用程序中线程数量的影响:
如果您对处理大量客户的一般任务感兴趣,这里是关于这个问题的经典网络论文。
If you have threads which are dedicated only to sending or receiving data over network, then thread blocking won't be a problem, as only that dedicated thread will be blocked.
Then, let's consider impact of this solution on number of threads in your application:
If you interested in general task of handling lots of clients, here is the classic web paper on this question.
首先,您应该使用 java.nio 来获取非阻塞 I/O。假设由于某种原因您不能...
您可以轻松地让服务器使用 DatagramSocket 和工作队列(例如 java.util.concurrent.ThreadPoolExecutor)处理来自多个客户端的数据。
这个想法是,您有一个读取套接字的接收器线程,并且接收每个数据报,将其包装在“ReceivedDatagram”对象中并放入工作队列中。工作队列有一个线程池,其线程出队并处理每个数据包;如果数据包需要响应,线程会在阻塞之前发送响应(阻塞)以使另一个 ReceivedDatagram 出列。
要异步发送数据,您只需将一个“SendDatagram”对象放在工作队列上,它代表要发送的 DatagramPacket。
请注意,您将使用 Datagram.receive(DatagramPacket) 和 Datagram.send(DatagramPacket)。
First, you should use java.nio to get non-blocking I/O. Assuming you can't, for some reason...
You can easily have your server handle data from multiple clients using DatagramSocket and a work-queue, such as java.util.concurrent.ThreadPoolExecutor.
The idea is that you have a single receiver thread reading the socket, and each datagram is received, wrapped in a "ReceivedDatagram" object and dropped onto the work-queue. The work-queue has a thread pool whose threads dequeue and process each packet; if the packet requires a response, the thread sends the response (blocking) before blocking to dequeue another ReceivedDatagram.
To send data asynchronously, you simply put a "SendDatagram" object on the work-queue which represents a DatagramPacket to send.
Note, you will be using Datagram.receive(DatagramPacket) and Datagram.send(DatagramPacket).
您可以通过在单独的线程中执行阻塞操作、使用手动生成的线程或更好的线程池来实现这一点 (http://www.ibm.com/developerworks/library/j-jtp0730.html)
You can do that by doing blocking operations in separate threads, using either manually spawned thread or better Thread Pool (http://www.ibm.com/developerworks/library/j-jtp0730.html)