java 中断 DatagramSocket.receive 中的一个线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4670664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:26:28  来源:igfitidea点击:

Interrupt a thread in DatagramSocket.receive

javamultithreadingsockets

提问by SEK

I'm building an application that listens on both TCP and UDP, and I've run into some trouble with my shutdown mechanism. When I call Thread.interrupt()on each of the listening threads, the TCP thread is interrupted from listening, whereas the UDP listener isn't. To be specific, the TCP thread uses ServerSocket.accept(), which simply returns (without actually connecting). Whereas the UDP thread uses DatagramSocket.receive(), and doesn't exit that method.

我正在构建一个同时侦听 TCP 和 UDP 的应用程序,但我的关闭机制遇到了一些麻烦。当我调用Thread.interrupt()每个侦听线程时,TCP 线程被中断侦听,而 UDP 侦听器没有。具体来说,TCP 线程使用ServerSocket.accept(),它只是返回(没有实际连接)。而 UDP 线程使用DatagramSocket.receive(), 并且不退出该方法。

Is this an issue in my JRE, my OS, or should I just switch to (Datagram)Socket.close()?

这是我的 JRE、我的操作系统中的问题,还是我应该切换到(Datagram)Socket.close()

UPDATE: I've found an analysisof the problem. It confirms that the behavior is not consistent.

更新:我找到了对问题的分析。它确认行为不一致。

回答by John Vint

A common idiom for interrupting network IO is to close the channel. That would be a good bet if you need to effectively interrupt it while its waiting on sending or receiving.

中断网络 IO 的一个常见习惯用法是关闭通道。如果您需要在等待发送或接收时有效地中断它,那将是一个不错的选择。

public class InterruptableUDPThread extends Thread{

   private final DatagramSocket socket;

   public InterruptableUDPThread(DatagramSocket socket){
      this.socket = socket;
   }
   @Override
   public void interrupt(){
     super.interrupt();  
     this.socket.close();
   }
}

回答by JOTN

As far as I know, close()is the proper way to interrupt a blocked socket. Interrupting and keeping open something that may have already done a partial read or write makes things unnecessarily complex. It's easier to only have to deal with a "success" or "give up" result.

据我所知,close()是中断阻塞套接字的正确方法。中断并保持打开可能已经完成部分读取或写入的内容会使事情变得不必要地复杂。只需要处理“成功”或“放弃”的结果会更容易。

回答by Navi

DatagramSocket.receiveblocks until it receives a datagram. Probably what you need to do is use setSoTimeoutto make it timeout.

DatagramSocket.receive阻塞直到它收到一个数据报。可能您需要做的是使用setSoTimeout它来超时。