简体   繁体   English

我可以唤醒由于调用DatagramSocket.receive()而阻塞的线程吗?

[英]Can I wake a thread that has blocked because of a call to DatagramSocket.receive()?

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. 我有一个线程在UDP数据包上阻塞,我需要能够告诉它忘记该数据包,然后在接收超时发生之前全部执行其他操作。 Is there any way to do this? 有什么办法吗?

Use a DatagramChannel to read your UDP packets, and interrupt the reading thread. 使用DatagramChannel读取UDP数据包,并中断读取线程。 As per the documentation of Thread.interrupt (and DatagramChannel), the read operation will then throw a ClosedByInterruptException. 根据Thread.interrupt(和DatagramChannel)的文档,读取操作将随后引发ClosedByInterruptException。

JB has posted one part of the solution. JB发布了解决方案的一部分。 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. 但是,如果您不使用NIO通道,则解决方案AFAIK此处将考虑关闭套接字,并在您可运行/可调用的情况下同样处理它。 I did something similar a while back with TCP sockets, in case if you are interested. 不久前, 我对 TCP套接字做了类似事情 ,以防您感兴趣。 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. 在这种情况下,采用NIO解决方案将更加有意义。

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. 设置一个短得多的读取超时,并让您的read方法循环正确的次数,然后它才认为发生了读取超时。 In the other (n-1) cases have it check Thread.isInterrupted(). 在其他(n-1)种情况下,请检查Thread.isInterrupted()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM