Interrupt a thread in DatagramSocket.receive

前端 未结 3 1284
孤城傲影
孤城傲影 2020-12-17 09:03

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 eac

3条回答
  •  甜味超标
    2020-12-17 09:52

    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.

    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();
       }
    }
    

提交回复
热议问题