如何中断等待接收 udp 数据包的线程?

How to interrupt a thread from waiting to receive a udp packet?

我有以下代码:

    public class ServerConnectionListener implements Runnable {


    DatagramSocket receiveSocket;
    DatagramPacket receivePacket;
    /*
    Some Initilization here in the constructor 
    //
    //
    */


    @Override
    public void run() 
    {
    try {        
         System.out.println("Waiting..."); // so we know we're waiting
         receiveSocket.receive(receivePacket);
      } catch (IOException e) 
         {
         System.out.print("IO Exception: likely:");
         e.printStackTrace();
         System.exit(1);
         }

    //Some more stuff to be done here

    }
 }

我知道 receiveSocket.receive() 是一个阻塞调用。因此,我想以这样一种方式使用 Thread.currentThread().isInterrupted(),这样我就可以中断这个线程,而不必再等待数据包被接收。

您不能安全地中断在套接字接收上阻塞的线程。

完成此操作的简单方法是设置合理的超时值 (DatagramSocket.setSoTimeout(int milliseconds)),即 1 秒,并在每个 SocketTimeoutException.

上检查中断标志

更好但更复杂(从编码的角度来看)的解决方案是使用 java.nio.channels.

的工具