我可以唤醒因调用 DatagramSocket.receive() 而阻塞的线程吗?
我有一个线程阻塞 UDP 数据包,我需要能够告诉它忘记该数据包并执行其他操作,所有这些都在接收超时发生之前进行。有什么办法可以做到这一点吗?
I have a thread that blocks on a UDP packet, and I need to be able to tell it to forget about that packet and do something else, all before the receive timeout happens. Is there any way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 DatagramChannel 读取 UDP 数据包,并中断读取线程。根据 Thread.interrupt(和 DatagramChannel)的文档,读取操作将抛出 ClosedByInterruptException。
Use a DatagramChannel to read your UDP packets, and interrupt the reading thread. As per the documentation of Thread.interrupt (and DatagramChannel), the read operation will then throw a ClosedByInterruptException.
JB 发布了解决方案的一部分。但是,如果您不使用 NIO 通道,那么这里的解决方案 AFAIK 是考虑关闭套接字并在您的可运行/可调用中以同样的方式处理它。 我做了类似的事情< /a> 不久前的 TCP 套接字,如果您有兴趣的话。该解决方案的可行性再次取决于您的情况是否可以接受关闭套接字。在这种情况下,采用 NIO 解决方案会更有意义。
JB has posted one part of the solution. But if in case you are not using NIO channels, the solution AFAIK here would be to close the socket in consideration and handle it likewise in your runnable/callable. I did something similar a while back with TCP sockets, in case if you are interested. The feasibility of the solution again depends on whether closing the socket would be acceptable in your case or not. In that case, going with the NIO solution would make much more sense.
设置更短的读取超时,并让您的读取方法在认为发生读取超时之前循环正确的次数。在其他 (n-1) 种情况下,让它检查 Thread.isInterrupted()。
Set a much shorter read timeout and have your read method loop the correct number of times before it considers a read timeout to have happened. In the other (n-1) cases have it check Thread.isInterrupted().